作为一个全局变量在类外做声明?

2024-09-27 07:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎这是唯一一种方法,我知道如何在一个不同的类中只从class-def中提取变量,而不需要在类中拥有我想调用变量的所有打印和函数。我是对的还是有其他更简单的方法?在

class MessageType:
    def process_msg1(self,data)
        item1 = []
        item2 = []
        item3 = []

        item1.append(float(stuff)*stuff)
        item2.append(float(stuff)*stuff)
        item2.append(float(stuff)*stuff)
        print('printing and plotting stuff')

        return(array(item1), array(item2), array(item3))

class PrintMSG(MessageType):
    def process_msg1(self, data):
        (i1, i2, i3) = messagetype.process_msg1(data)
        print('printing plus plotting using variables from class Message')

#processing piece
keep_asking = True
while keep_asking:
    command_type = input("What message type do you want to look at?")
    if command_type == 'msg type1':
        msg = MessageType()
        print_msg = PrintMSG()
        messagetype.process_msg1(self,data)
        print_msg.process_msg1(data)
    elif:
        print('other stuff')
    wannalook = input('Want to look at another message or no?')
    if not wannalook.startswith('y'):
        keep_asking = False

我遇到的问题是我有一个项目,我需要从其他类内部的其他类调用变量。我还有其他几个类具有全局变量,但我的问题是(i1, i2, i3) = messagetype.process_msg1(data)再次运行整个class-def,而不是仅仅调用数组变量。如果在#processing piece下我已经调用了class-def,有没有办法调用它们?在

引用上一个发布的问题here!在


Tags: selfdatadefmsgfloatarrayprocessclass
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:16

类应该是独立的代码和数据单元。拥有多个带有多个全局变量的类表明您几乎肯定做错了什么。在

类数据应该保存到self中,这些数据应该比单个方法调用持续更长时间,无论是以后在内部使用还是公开给其他代码。因此您的item1item2和{}应该在__init__方法中初始化,然后{}应该在不初始化它们的情况下更新它们。像这样:

class MessageType:

    def __init__(self):
        self.item1 = []
        self.item2 = []
        self.item3 = []

    def process_msg1(self, data)
        self.item1.append(float(stuff) * stuff)
        self.item2.append(float(stuff) * stuff)
        self.item2.append(float(stuff) * stuff)
        print('printing and plotting stuff')
        return(array(self.item1), array(self.item2), array(self.item3))

然后,一旦您创建了一个实例(message_type = MessageType())并调用了process_msg1方法(message_type.process_msg1(1.0, 2.3, 3.14159)),其他代码就可以以message_type.item1的形式访问它,等等)。在

相关问题 更多 >

    热门问题