2014-04-25 51 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