Reputation: 774
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?
Upvotes: 0
Views: 215
Reputation: 79
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.
Upvotes: 0
Reputation: 531325
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.
Upvotes: 0
Reputation: 42758
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.
Upvotes: 2