# 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)
答案 0 :(得分:1)
当您实例化一个类时,您不需要传入base_class
。这是根据定义完成的。 __init__
只需要1个参数,即self
,并且是自动的。你只需要打电话
project_class = Project()
答案 1 :(得分:1)
要使Project继承自Base,您不应该从对象继承它,而是从Base继承它,即class Project(Base)
。实例化Project类时出现TypeError: init() takes exactly 1 argument (2 given)
错误,因为构造函数只接受1个参数(self
)并且您也传递base_class
。 'self'
由python隐式传递。
答案 2 :(得分: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