考虑下面的代码片段,超和子类共享变量
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
,你可以看到,我有一个基类和派生类。我希望派生类设置可在程序外部使用的“变量”。例如,子类正在执行复杂任务并设置变量,该变量将被其他类和函数使用。
但是到现在为止,由于子类具有自己的实例,因此它不会反映到范围之外。
是否有解决此问题的方法?
@毛毛
class super():
def __init__(self):
self.variable = ''
def setVariable(self, value):
self.variable = value
class child():
def __init__(self, instance_of_super):
self.handle = instance_of_super
self.setSuperVariable()
def setSuperVariable(self):
# according to this variable should have value 10
self.handle.setVariable(10)
super_instance = super()
child1 = child(super_instance)
print super_instance.variable
# prints nothing
super_instance.setVariable(20)
print super_instance.variable
这将设置变量。虽然我不使用继承。 :)
不要使用'super'作为类名;它掩盖了内置函数,它可以在重写父类的方法时派上用场。 –
作为@MartijnPieters,你刚刚通过屏蔽'super()'内建了大部分不可用的Python继承。 – ElmoVanKielmo
我真的不明白你的问题是什么。你永远不会实例化'child',也不会调用'setSupetVariable',所以你不清楚你有什么问题。如果你确实做了这些事情,那么'child.variable'就是10. –