Python. Class inheritance. Rules




Python. Class inheritance. Rules for applying inheritance. Examples


Contents


Search other resources:

1. Implementation of inheritance in classes. General concepts

Like other programming languages, Python implements the inheritance mechanism. Inheritance – is the ability to extend (inherit) a previously written program code of a class in order to supplement, improve or bind to new requirements.

Inheritance allows you to create a hierarchies of classes. In these hierarchies, the upper-level classes represent the most generalized attributes, and the lower-level classes (subclasses) implement more detailed attribute specialization. Class hierarchies form a hierarchy tree in which the lower the class is, the more specialized it is.

If one class inherits (extends) another class, then that class is called a subclass. And the class that inherits is called the superclass.

 

2. Rules governing how Python inheritance works. Examples

In the Python language, inheritance is implemented according to the following rules.

2.1. Rule 1. Specifying the name of the superclass

If a class inherits from another superclass, then the name of the superclass is specified in parentheses in the header of the class statement.

For example.

# Class A - is the superclass for class B
class A:
    # class A attributes
    ...

# Class B - is a subclass of class A
class B(A):
    # class B attributes
    ...

 

2.2. Rule 2. Inheriting superclass attributes by subclass

The subclass inherits the attributes of its superclasses.

For example.

# Class A - is a superclass for classes B, C
class A:
    # Class A attribute: AAA() method
    def AAA(self):
        print("class A. Method AAA()")

# Class B - is a subclass of class A
class B(A):
    # Class B attribute: BBB() method
    def BBB(self):
        # From the BBB() method
        # you can access the AAA() attribute of class A
        self.AAA() # will be invoked A.AAA()
        print("class B. Method BBB()")

# Class C - is a subclass of classes A, B
class C(B):
    # Class C attribute: CCC() method
    def CCC(self):
        # From the CCC() method, you can access the AAA()
        # attribute of class A and the BBB() attribute of class B.
        self.AAA()
        self.BBB()
        print("class C. Method CCC()")

# Testing the inheritance mechanism
# 1. Using an instance of class A
objA = A()
objA.AAA() # call the AAA() method of class A
print("----------------")

After launching for execution, the program produced the following result

class A. Method AAA()
----------------
class A. Method AAA()
class A. Method AAA()
class B. Method BBB()
----------------
class A. Method AAA()
class A. Method AAA()
class B. Method BBB()
class A. Method AAA()
class A. Method AAA()
class B. Method BBB()
class C. Method CCC()

 

2.3. Rule 3. Inheritance of superclass attributes by subclass instance

Instances of classes inherit the attributes of all available classes. For example. From the objB instance, you can access the methods (attributes) A1(), A2(), A3() of class A.

# Class A - is the superclass for class B
class A:
    # Class A attributes:
    def A1(self):
        print("A.A1()")

    def A2(self):
        print("A.A2()")

    def A3(self):
        print("A.A3()")

# Class B - is the subclass of class A
class B(A):
    # Class B attributes:
    def B1(self):
        print("B.B1()")

# Access from an instance of subclass B
objB = B()

# Calling methods of superclass A
objB.A1()
objB.A2()
objB.A3()

Program execution result

A.A1()
A.A2()
A.A3()

 

2.4. Rule 4. Accessing a superclass attribute from a class instance

To access a superclass attribute from a class instance, you need to do a call like

obj.attribute

here

  • obj – subclass instance name;
  • attribute – the name of the superclass attribute.

Such appeal includes:

  • reference to instances and classes by class statement (e.g. A.attribute);
  • a reference to the attributes of the instance argument self in the class methods (e.g. self.attribute).

Examples of the use of this rule are given in the previous two rules 3.

 

2.5. Rule 5. Changes to a subclass do not affect the superclass. Attributes overloading

If changes are made to the subclass, the changes do not affect the superclass. This also applies to replacing the names of superclasses in subclasses at a lower level in the class tree. In this case, only the inherited behavior is changed. Replacing the attributes of a superclass by overriding them in subclasses is called overloading.

For example. The following code demonstrates how to replace the HelloWorld() method name of class A in subclass B.

# Class A is the superclass for class B
class A:
    # Class A Attribute - HelloWorld() method
    def HelloWorld(self):
        print("Class A: Hello world!")

# Class B is a subclass of class A
class B(A):
    # Class B has an attribute with the same name as class A
    def HelloWorld(self):
        print("Class B: Hello world!")

# Demonstrate name substitution
# 1. Declare an instance of class B
objB = B()

# 2. Invoke method HelloWorld()
objB.HelloWorld() # Class B: Hello world! - the method of class B

# 3. Declare an instance of class A
objA = A()

# 4. Invoke method HelloWorld()
objA.HelloWorld() # Class A: Hello world! - the method of class A

The result of the program

Class B: Hello world!
Class A: Hello world!

As you can see from the result, replacing the method name in subclass B does not affect the method of the same name in class A.

 

3. An example of using inheritance. Extending the Point class to the ColorPoint class

Task. A Point class is specified that describes a point with coordinates x, y on the coordinate plane. Using the inheritance mechanism, you need to extend the capabilities of the Point class by adding a new color attribute. To do this, implement a PointColor subclass.

Implement the following attributes in the Point class:

  • point coordinates;
  • an initialization method that receives 2 parameters – the coordinates of the point x, y;
  • method for calculating the distance from a point to the origin;
  • the getPoint() method, which returns the point as a list.

In the PointColor subclass, implement the following attributes:

  • the color of point (color);
  • initialization method, which takes 3 parameters: point coordinates and color;
  • access method to the color named getColor().

Solution. The program text that solves the problem is as follows.

import math

# Class describing a point on a coordinate plane
class Point:
    # Initialization method for class data
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Method for calculating distance from point to origin
    def length(self):
        # Pythagorean theorem
        len = math.sqrt(self.x*self.x+self.y*self.y)
        return len

    # A method that returns the coordinates of a point as a list
    def getPoint(self):
        return [self.x, self.y]

# Class that extends the Point class
class PointColor(Point):
    # Initialization method
    def __init__(self, x, y, color):
        # access to x, y of Point superclass
        self.x = x
        self.y = y

        # introduce a new variable color
        self.color = color

    # Return the color
    def getColor(self):
        return self.color;

# Using the Point class
point1 = Point(3, 4)
print("point1.length = ", point1.length()) # length = 5.0
print("point11 = ", point1.getPoint())

# Using the PointColor class
point2 = PointColor(5, 6, "Red")
print("point2.x = ", point2.getPoint()[0])
print("point2.y = ", point2.getPoint()[1])
print("point2.color = ", point2.getColor())

The result of the program

point1.length = 5.0
point11 = [3, 4]
point2.x = 5
point2.y = 6
point2.color = Red

 


Related topics