Introduction to Python Inheritance
Python classes can inherit attributes and methods from other classes. For example, suppose that the Dog class is a child of the Animal class. If the Animal class contains a method called move, then we can call the move method with Dog class objects even if the Dog class does not contain the move method.
Let's take a look at an example:
| Current Line | 1 | Current Tab | 0 | Time | 0 |
In the example above, the Animal class is the parent, or base, class and Dog is the child, or derived, class. The Animal class contains 2 methods:
- __init__
- move
The Dog class contains neither of these methods, but it contains another method called jump.
In line 10, Python constructs a Dog object. Python first looks in the Dog class for the __init__ method. The Dog class does not contain the __init__ method, so Python next looks in the base class of Dog, which is the Animal class. The Animal class does contain the __init__ method at line 2, so Python executes the Animal.__init__ method body. Note that, since Python is creating a Dog object, self is an instance of Dog rather than Animal.
After the constructor call is finished, the new Dog object is assigned to joe. joe contains attributes x and y, even though the Dog class definition never references attribute x.
In line 11, we call the move method with joe. Since joe is a Dog, Python looks for the move method in the Dog class. The Dog class does not contain the move method, so Python again looks in the base class. The Animal class contains the move method in line 5, so Python executes the Animal.move() method.
Finally, in line 12, we call the jump method with joe. The Dog class does contain the jump method, so Python executes the jump method at line 9.
Inheritance is very useful when we want to model objects that share some, but not all, characteristics. For example, suppose that we want to model cats and dogs. They both walk on 4 legs, but cats have whiskers while dogs have long muzzles. We can create a Pet class that contains attributes and methods that are common for both cats and dogs, and the Dog and Cat classes can derive from the Pet class.
Consider the simulator above. After line 10 has been executed, what is the value of joe.x?
Consider the simulator above. After line 11 has been executed, what is the value of joe.x?
Consider the simulator above. After line 12 has been executed, what is the value of joe.y?
Comments
Please log in to add comments