2017-04-25 73 views
0

我在類的init()方法中定義了一個實例變量,並從中派生出一個新類。當我嘗試從輔助類的實例引用此變量時,它似乎沒有被繼承。如何在Python中引用實例變量

這是代碼:

company=Company() 
person=Person() 
task=Task() 

print(company.get_attrs()) 

class Entity(Persistent): 
    list_of_attrs=[] 
    list_of_attrs_flag=False 

    def __init__(self): 
     attributes={} 
     attributes_edition_flag={} 
     if not type(self).list_of_attrs_flag: 
      type(self).list_of_attrs=self.get_attrs_from_persistent() 
      type(self).list_of_attrs_flag=True 
      for attr in type(self).list_of_attrs: 
       attributes[attr]='' 
       attributes_edition_flag[attr]='false' 

    def get_attrs(self): 
     return(self.attributes) 

class Company(Entity): 
    def hello(self): 
     print('hello') 

這是我的錯誤:

MacBook-Pro-de-Hugo:Attractora hvillalobos$ virtual/bin/python3 control.py 
Traceback (most recent call last): 
    File "control.py", line 7, in <module> 
    print(company.get_attrs()) 
    File "/Users/hvillalobos/Dropbox/Code/Attractora/model.py", line 48, in get_attrs 
    return(self.attributes) 
AttributeError: 'Company' object has no attribute 'attributes' 

這是工作,但我感動的東西(我猜的),但我不能發現什麼。 感謝您的幫助

回答

5

在您的__init__方法中,您必須使用self.attributes而不是attributes

+0

這是正確的。然而,我必須提到,不是'type(self)'而是使用'self .__ class__'來訪問類屬性更爲正確。我想知道爲什麼OP使用字符串'false'而不是布爾值。 – RobertB

+0

謝謝@RobertB。我正在使用一個字符串,因爲它是一個字典(代碼錯誤地錯過了索引)。我可以使用字符串以外的數據類型作爲字典的值嗎? –

+0

嘗試一下,找出答案。 – RobertB