>  기사  >  백엔드 개발  >  Python에서 상위 클래스를 다시 작성하는 방법은 무엇입니까?

Python에서 상위 클래스를 다시 작성하는 방법은 무엇입니까?

PHPz
PHPz앞으로
2023-05-04 23:52:132014검색

1. 기본 적용

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. 실제 적용

#用元类实现单例模式
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. 참고

1. 클래스가 다중 상속을 받는 경우 상속받은 여러 상위 클래스는 동일한 상위 클래스 A를 갖게 됩니다. 주의할 점

방법 1: 부모 클래스 이름. 메서드 이름(객체)

  • 부모 클래스 A는 (상속 횟수에 따라) 여러 번 호출됩니다.

  • 부모 클래스를 다시 작성할 때 필요에 따라 필수 정보를 제공해야 합니다.

2. 클래스에 상속이 있고 해당 변수가 하위 클래스에 다시 작성되면 상위 클래스의 변수를 변경해도 하위 클래스에 영향을 주지 않습니다

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)
    출력 결과
  • 1 1 1
  • 1 2 1
  • 3 2 3

위 내용은 Python에서 상위 클래스를 다시 작성하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제