繁体   English   中英

Python的类继承

[英]Python's Class Inheritance

# 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)

当实例化一个类时,不需要传递base_class 这是按定义完成的。 __init__接受1个参数,它是self ,并且是自动的。 你只需要打电话

project_class = Project()

为了使Project从Base继承,您不应从Object继承它,而应从Base继承它,即class Project(Base) 您会得到TypeError: init() takes exactly 1 argument (2 given)实例化Project类时, TypeError: init() takes exactly 1 argument (2 given)错误,因为构造函数仅接受1个参数( self ),并且还传递了base_class 'self'由python隐式传递。

您的代码中有两个错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM