简体   繁体   中英

Python class instance variables inheritance mechanics

If I run this code:

class Super:    
    def __init__(self, name):
        self.name = name


class Sub(Super):
    def publ(self):
        print("works")

a = Sub()

as planned it succesfully fails with this message:

TypeError: __init__() takes exactly 2 arguments (1 given)

but it gives me bugging question:

Where the information is stored about Sub class requirement for the argument entry? I mean how SUB() knows that it needs "name" as the argument? What is mechanism defining how it inherits "that knowledge" from Super().

The Python Tutorial has a section on inheritance .

if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

What happens when you call Sub() is that the interpreter looks in the class object for an attribute named __init__ . If it finds one it will use it. If it doesn't find it (which is the case in your example), it will search through the class's base classes. In your example it finds the __init__ method inherited from class Super . The interpreter will proceed to call that method.

You can fix your example in either of the following ways:

a = Sub('John Doe')

or:

class Sub(Super):
    def __init__(self):
        super(Sub, self).__init__("My Name Is Sub")

    def publ(self):
        print("works")

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