2011-11-30 48 views
-2
class Test1: 
    def __init__(self): 
     self.x = 1 

class Test2(Test1): 
    # how can I get parent class's self.x ?? 
    # exactly here not def __init__(self) or other methods in Test2.. 

請...我花了幾個小時搞清楚如何讓父類的自我!並失敗.. 我需要一個Python專家!我怎樣才能獲得父母的自我?

+1

你能解釋爲什麼你需要「父類的self.x」嗎? – seb

回答

2

你要這樣呢?

class Test1: 
    def __init__(self): 
     self.x = 1 

class Test2(Test1): 
    def __init__(self): 
     Test1.__init__(self) 
     print self.x 

a = Test2() 

您可以訪問Test2內部的self.x,因爲Test2對象具有x屬性。它在Test1初始化器中創建。

編輯:作者解釋我的誤解後,這是不可能的事是問,因爲x是一個實例成員,而不是一類一。查看gecco的答案。

+0

抱歉..不,這不是我的意思......不是「高清__init __(個體經營)」,但在類定義的一部分。「Test2的類」 – Anderson

+0

然後gecco的答案是正確的。 –

+0

非常感謝。 Thiago Chaves – Anderson

2

這是不可能的。 self.x是一個實例變量。實例變量只能從實例方法中訪問。你在靜態環境中的外部方法。

你可以這樣做(純類變量(不是實例)):

class Test1: 
    x = 1 

class Test2: 
    y = Test1.x 
+0

謝謝..嗯..我需要找到另一種方式..非常感謝。 – Anderson

2

在類定義的角度來看,有沒有對象,所以沒有self - self只有裏面的含義成員函數。無論如何,你想在類定義中使用self.x什麼?

+0

其實..我搞清楚這個.. [鏈接](http://stackoverflow.com/questions/8326361/using-key-as-value-in-mongoengine)我想這需要一些黑客..也許。 。 – Anderson

+0

@WebEngineer:這個問題很難理解,但就我所知,你必須研究元類來解決這個問題。 –

+0

非常感謝。比約恩波利斯。 – Anderson