Python重写父类的方法有哪些

其他教程   发布日期:2024年05月09日   浏览次数:374

这篇文章主要介绍了Python重写父类的方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python重写父类的方法有哪些文章都会有所收获,下面我们一起来看看吧。

1.基础应用

  1. class Animal(object):
  2. def eat(self):
  3. print("动物吃东西")
  4. class Cat(Animal):
  5. def eat(self):
  6. print("猫吃鱼")
  7. # 格式一:父类名.方法名(对象)
  8. Animal.eat(self)
  9. # 格式二:super(本类名,对象).方法名()
  10. super(Cat, self).eat()
  11. # 格式三:super()方法名()
  12. super().eat()
  13. cat1 = Cat()
  14. cat1.eat()
  15. print(cat1)

2.实际应用

  1. #用元类实现单例模式
  2. class SingletonType(type):
  3. instance = {}
  4. def __call__(cls, *args, **kwargs):
  5. if cls not in cls.instance:
  6. # 方式一:
  7. # cls.instance[cls] = type.__call__(cls, *args, **kwargs)
  8. # 方式二
  9. # cls.instance[cls] = super(SingletonType, cls).__call__(*args, **kwargs)
  10. # 方式三
  11. cls.instance[cls] = super().__call__(*args, **kwargs)
  12. return cls.instance[cls]
  13. class Singleton(metaclass=SingletonType):
  14. def __init__(self, name):
  15. self.name = name
  16. s1 = Singleton('1')
  17. s2 = Singleton('2')
  18. print(id(s1) == id(s2))

3.注意

1.当一个类存在多继承时,它继承的多个父类有相同的父类A,在重写其父类时需要注意

方法一:父类名.方法名(对象)

  • 父类A会被调用多次(根据继承的个数)

  • 重写父类时根据需要传递所需要的参数

方法二:super(本类名,对象).方法名()

  • 父类A也只会被调用一次

  • 重写父类方法必须传递所有参数

2.当一个类存在继承,且已经在子类中重写相应的变量,改变父类的变量不会对子类有影响

  1. class Parent(object):
  2. x = 1
  3. class Child1(Parent):
  4. pass
  5. class Child2(Parent):
  6. pass
  7. print(Parent.x, Child1.x, Child2.x)
  8. Child1.x = 2
  9. print(Parent.x, Child1.x, Child2.x)
  10. Parent.x = 3
  11. print(Parent.x, Child1.x, Child2.x)

输出结果

1 1 1
1 2 1
3 2 3

以上就是Python重写父类的方法有哪些的详细内容,更多关于Python重写父类的方法有哪些的资料请关注九品源码其它相关文章!