# 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)
Tags:
代码中有两个错误:
1)类继承
2)实例定义(您的
__init__
不需要任何显式参数,当然也不需要祖先类)实例化类时,不需要传入
base_class
。从定义上讲就是这样。__init__
只接受一个参数,即self
,并且是自动的。你只需要打个电话对于要从基继承的项目,您不应该从对象而从基继承它的子类,即
class Project(Base)
。实例化项目类时会出现TypeError: init() takes exactly 1 argument (2 given)
错误,因为构造函数只接受1个参数(self
),而您也传递了base_class
。'self'
由python隐式传递。你知道吗相关问题 更多 >
编程相关推荐