简体   繁体   中英

Why does it work when a parent class method access a child object in python even though it is defined later?

Question related with inheritance in python.

why is it correct to use a child class object inside a parent class method, while the child class is defined later in the code? How does python know the child class will be defined later in the code? When does the class statements gets executed?

Python is a dynamic language. So every name is resolved at runtime. No need to know, which names are defined when class methods are defined.

The reason is that you are accessing Child in the body of the method, which is not evaluated when the method is defined . If you were to try to call the method while defining the parent, you would still get an error. Consider:

class Parent(object):
    def __init__(self):
        # OK, as long as `__init__` isn't called
        # until after Child is defined.
        self.child = Child(x)


p = Parent(3)   # Wrong! Child isn't defined yet

class Child(Parent):
    def __init__(self, x):
        pass

p = Parent(3)   # OK; Child is now defined.

Defining a class does not execute the code inside the body. It simply binds the the class object to a name so that it can be called later on. If both classes are created or in other words a class object is bound to a class name variable then both can be called in any order. A variable must be created by binding it to an object before you can use it. This is what happens in functions and classes. the function or class name is the variable and the body is the value.

Although this will run, doing this is very bad style and I would refrain from ever doing this. It's ok for a child to call a parent method but not the other way around.

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