2014-04-25 52 views
0

考虑下面的代码片段,超和子类共享变量

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 

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

+3

不要使用'super'作为类名;它掩盖了内置函数,它可以在重写父类的方法时派上用场。 –

+0

作为@MartijnPieters,你刚刚通过屏蔽'super()'内建了大部分不可用的Python继承。 – ElmoVanKielmo

+1

我真的不明白你的问题是什么。你永远不会实例化'child',也不会调用'setSupetVariable',所以你不清楚你有什么问题。如果你确实做了这些事情,那么'child.variable'就是10. –

回答

0

由于继承在类级别工作,因此在修改子实例时,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 

输出是:

None 
None 
10 
10 
+0

感谢您的回复。我脑子里有同样的事情。但我也有一个替代解决方案。作为一个参数,我可以将超类的实例处理程序传递给子类,而不是继承。通过我可以访问所有的变量,其范围将贯穿整个程序。但我想检查是否有其他方法或解决方法。感谢您的时间和回应。 – Bala