2014-01-08 174 views
0
# Defining a Base class to be shared among many other classes later: 

class Base(dict): 
    """Base is the base class from which all the class will derrive. 
    """ 
    name = 'name'  
    def __init__(self): 
     """Initialise Base Class 
     """ 
     dict.__init__(self) 
     self[Base.name] = "" 

# I create an instance of the Base class: 

my_base_instance = Base() 

# Since a Base class inherited from a build in 'dict' the instance of the class is a dictionary. I can print it out with: 

print my_base_instance Results to: {'name': ''} 


# Now I am defining a Project class which should inherit from an instance of Base class: 

class Project(object): 
    def __init__(self): 
     print "OK" 
     self['id'] = '' 

# Trying to create an instance of Project class and getting the error: 

project_class = Project(base_class) 

TypeError: __init__() takes exactly 1 argument (2 given) 
+4

您必須在定義類('class Project(Base)')時聲明繼承,而不是在實例化時聲明繼承。 – Hyperboreus

回答

1

有兩個錯誤在你的代碼:

1)類繼承

class Project(Base): # you should inherit from Base here... 
    def __init__(self): 
     print "OK" 
     self['id'] = '' 

2)實例的定義(您__init__並不需要任何明確的參數,而且可以肯定不是祖先類)

project_class = Project() # ...and not here since this is an instance, not a Class 
1

當你正在實例化一個類時,你不需要傳入base_class。這是定義完成的。 __init__只需要1個參數,即self,並且是自動的。你只需要調用

project_class = Project() 
1

對於項目從基本繼承,你不應該從對象繼承它,但來自基地即class Project(Base)。當您實例化Project類時,您會收到TypeError: init() takes exactly 1 argument (2 given)錯誤,因爲構造函數只帶1個參數(self),並且您也通過base_class。由python隱式傳遞'self'