超小班共享变量

2024-09-27 09:27:17 发布

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

考虑下面的代码片段

class super1():
    def __init__(self):
        self.variable = ''

    def setVariable(self, value):
        self.variable = value

class child(super1):
    def __init__(self):
        super.__init__(self)
        self.setSuperVariable()

    def setSuperVariable(self):
        # according to this variable should have value 10
        self.setVariable(10)

super_instance = super1()
child1 = child()

print super_instance.variable
# prints nothing

super_instance.setVariable(20)
print super_instance.variable

如您所见,我有一个基类和一个派生类。我希望派生类设置可以在程序外使用的“变量”。例如,子类正在执行come complex任务并设置变量,该变量将被其他类和函数使用。在

但是到目前为止,由于子类有自己的实例,所以它没有被反映到作用域之外。在

有解决这个问题的方法吗?在

@艾尔莫

^{pr2}$

这将设置变量。虽然我没有使用继承。:)


Tags: instanceselfchildinitvaluedef子类variable
1条回答
网友
1楼 · 发布于 2024-09-27 09:27:17

修改子实例时,super1实例中的变量不会更改,因为继承是在类级别工作的。一旦你创建了一个实例,它就拥有了来自它自己和它的父对象的所有东西。每个实例都是完全独立的,一个实例中的更改不会反映到另一个实例上。在

您可以通过类属性获得这种副作用,而这正是您想要的,您根本不需要继承:

class MyClass:
    class_attribute = None

    @classmethod
    def set(cls, value):
        cls.class_attribute = value

    def do_computation(self):
        self.set(10)


a = MyClass()
b = MyClass()
print a.class_attribute
print b.class_attribute

a.do_computation()
print a.class_attribute
print b.class_attribute

输出为:

^{pr2}$

相关问题 更多 >

    热门问题