简体   繁体   中英

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)

When you're instantiating a class, you don't need to pass in base_class . That's done at definition. __init__ takes exactly 1 argument, which is self , and automatic. You just need to call

project_class = Project()

For Project to inherit from Base, you should not subclass it from object but from Base ie class Project(Base) . You get TypeError: init() takes exactly 1 argument (2 given) error when you instantiate Project class because the constructor takes only 1 parameter( self ) and you pass base_class too. 'self' is passed implicitly by python.

there are two mistakes in your code:

1) Class inheritance

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

2) Instance definition (your __init__ does not requires any explicit parameter, and for sure not the ancestor class)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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