2011-03-19 90 views
0

這是最佳實踐類型的問題。我要訪問從另一個屬性和一個類的方法(也許這本身就是一種不好的做法)和我在做什麼來實現這一目標是訪問其他類的屬性和方法的最佳實踐

class table(): 
    def __init__(self): 
     self.color = 'green' 
    colora = 'red' 

    def showColor(self): 
     print('The variable inside __init__ is called color with a value of '+self.color) 
     print('The variable outside all methos called colora has a value of '+colora) 

class pencil(table): 
    def __init__(self): 
     print('i can access the variable colora from the class wtf its value is '+table.colora) 
     print('But i cant access the variable self.color inside __init__ using table.color ') 

object = pencil() 
>>> 
i can access the variable colora from the class wtf its value is red 
But i can't access the variable self.color inside __init__ using table.color 
>>> 

正如你可以看到我正在做一個實例在課堂上定義的鉛筆,我使用符號從一個班級繼承到另一個班級。

我已經讀過無處不在的人聲明他們的類屬性init這是否意味着我不應該訪問其他類而不使用它的實例? 我認爲這是一個繼承問題,但我不能把這個概念帶進我的腦海,而且我已經在書籍和教程中閱讀了一些解釋。

最後,我只是想能夠訪問一個類與另一個類的屬性和方法。 謝謝

回答

3

更explixitly,如果你想從鉛筆訪問table.color,你不需要包裝在一個方法,但你需要調用表構造函數首先:

class table(): 

    colora = 'red' 
    def __init__(self): 
     self.color = 'green' 
     print 'table: table.color', self.color 
     print 'table: table.color', table.colora 

class pencil(table): 

    def __init__(self): 
     table.__init__(self) 
     print 'pencil: table.colora', table.colora 
     print 'pencil: pencil.color', self.color 
     print 'pencil: pencil.colora', pencil.colora 

obj = pencil() 

另一個無關的問題,這條線

對象=鉛筆()

隱藏着蟒蛇「對象」的象徵,極有可能不是一個好主意。

+0

哦,我看到了,我看到的教程有更復雜的例子的繼承困惑,但基本上我需要的是將父項傳遞給括號,然後調用父類的__init__,然後我將能夠訪問定義的所有屬性在__init__中,當然還有它的方法,當然還有它的「公共」屬性,比如任何類方法之外的屬性。 這是正確的嗎? – 2011-03-19 14:37:34

+1

是的,但所有屬性都是「公共」的,請參閱http://docs.python.org/tutorial/classes.html#private-variables。 「傳遞父項」表示您正在繼承它,構造函數調用可確保您通過self.attrubute_name訪問屬性。如果你不調用構造函數,你仍然可以訪問「colora」屬性,但不能訪問self.color。 – juanchopanza 2011-03-19 15:37:28

1

在正常方法中綁定到self的屬性只能通過調用該方法時作爲self傳遞的實例訪問。如果該方法從未通過實例調用過,則該屬性不存在。

類屬性的不同之處在於它們在創建類本身時被綁定。

另外,如果一個屬性以單個下劃線開頭(_),那麼如果可以幫助的話,絕對不要在類之外訪問它。

+0

哦,好吧,所有的屬性,我想從外部的類我需要首先「發佈」他們調用一個方法,返回他們的權利? – 2011-03-19 06:59:26

+0

是不是'_'用來表示在從模塊導入*'執行'時不會導入''? – user225312 2011-03-19 07:00:11

+1

@Guillermo:「創造它們」是一種更準確的觀察方式。 – 2011-03-19 07:03:40