Home  >  Article  >  Backend Development  >  What are the methods for rewriting parent classes in Python?

What are the methods for rewriting parent classes in Python?

PHPz
PHPzforward
2023-05-04 23:52:131934browse

1. Basic application

class Animal(object):
    def eat(self):
        print("动物吃东西")


class Cat(Animal):
    def eat(self):
        print("猫吃鱼")
        # 格式一:父类名.方法名(对象)
        Animal.eat(self)
        # 格式二:super(本类名,对象).方法名()
        super(Cat, self).eat()
        # 格式三:super()方法名()
        super().eat()


cat1 = Cat()
cat1.eat()
print(cat1)

2. Practical application

#用元类实现单例模式
class SingletonType(type):
    instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls.instance:
            # 方式一:
            # cls.instance[cls] = type.__call__(cls, *args, **kwargs)
            # 方式二
            # cls.instance[cls] = super(SingletonType, cls).__call__(*args, **kwargs)
            # 方式三
            cls.instance[cls] = super().__call__(*args, **kwargs)
        return cls.instance[cls]


class Singleton(metaclass=SingletonType):
    def __init__(self, name):
        self.name = name


s1 = Singleton('1')
s2 = Singleton('2')
print(id(s1) == id(s2))

3. Note

1. When a class has multiple inheritance, it inherits from multiple parents The classes have the same parent class A. When rewriting its parent class, you need to pay attention to

Method 1: Parent class name.Method name (object)

  • Parent class A Will be called multiple times (according to the number of inheritance)

  • Pass the required parameters as needed when overriding the parent class

Method 2 :super(class name, object).Method name()

  • The parent class A will only be called once

  • Rewrite the parent Class methods must pass all parameters

2. When a class has inheritance and the corresponding variables have been overridden in the subclass, changing the variables of the parent class will not affect the subclass.

class Parent(object):
    x = 1

class Child1(Parent):
    pass

class Child2(Parent):
    pass

print(Parent.x, Child1.x, Child2.x)
Child1.x = 2
print(Parent.x, Child1.x, Child2.x)
Parent.x = 3
print(Parent.x, Child1.x, Child2.x)

Output result

1 1 1
1 2 1
3 2 3

The above is the detailed content of What are the methods for rewriting parent classes in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete