Python的类Inheritan

2024-04-19 12:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

# 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: ofthetoinstancenamefromselfproject
3条回答

代码中有两个错误:

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

实例化类时,不需要传入base_class。从定义上讲就是这样。__init__只接受一个参数,即self,并且是自动的。你只需要打个电话

project_class = Project()

对于要从基继承的项目,您不应该从对象而从基继承它的子类,即class Project(Base)。实例化项目类时会出现TypeError: init() takes exactly 1 argument (2 given)错误,因为构造函数只接受1个参数(self),而您也传递了base_class'self'由python隐式传递。你知道吗

相关问题 更多 >