python继承

252 阅读2分钟

在Python中,继承是一种机制,允许我们基于已存在的类创建新类。新类继承了基类的所有属性和方法,并且可以添加或重写基类的方法。

  1. 单继承 示例:
class child:
    name = "王拿铁"
    age = None

    def school(self):
        print(f"我叫{self.name},我在读书")

class man(child):
    has_object = True

    def my_object(self):
        if self.has_object:
            print("我有对象了")
        else:
            print("我虽然成年了但我还是单身狗,")


man = man()
print(man.name)  # 王拿铁
man.school()  # 我叫王拿铁,我在读书
  1. 多继承
class class1:
    hi_type = "类1"

    def say_hi(self):
        print(f"我是{self.hi_type},我是say_hi方法")
        
class class2:
    hello_type = "类2"

    def say_hello(self):
        print(f"我是{self.hello_type},我是say_hell方法")

class class3:
    buy_type = "类3"

    def say_buy(self):
        print(f"我是{self.buy_type},我是say_buy方法")

class my_class(class1, class2, class3):
    # 如果类的代码块没有内容,可以使用pass关键字
    pass
 
cla = my_class()
print(cla.hi_type)     # 类1
print(cla.hello_type)  # 类2
print(cla.buy_type)    # 类3
cla.say_hi()           # 我是类1,我是say_hi方法
cla.say_hello()        # 我是类2,我是say_hell方法
cla.say_buy()          # 我是类3,我是say_buy方法

如果父类中存在一样名字的变量,那么会按照继承的顺序,谁先来的谁优先。

  1. 复写父类的方法。
class father:
    name = "父类"

    def say_fun(self):
        print(f"我是{self.name}的方法")
        
class child(father):
    name = "子类"

    def say_fun(self):
        print("我在子类中被重写了!")
        
child = child()
child.say_fun()  # 我在子类中被重写了!
  1. 在子类中,使用父类的变量或者方法
  • 通过父类名.变量名或方法使用
  • 通过super()..变量名或方法使用
class father:
    name = "父类"

    def say_fun(self):
        print(f"我是{self.name}的方法")
        
class child(father):
    name = "子类"

    def say_fun(self):
        # 使用父类名.变量调用父类的变量或者方法,使用父类.方法的时候必需传self
        print(f"父类中的name是:{father.name}")
        father.say_fun(self)
        # 使用super()调用父类的变量或者方法,
        super().say_fun()

多态

  1. 多态,指的是多种状态,即完成某个行为时,使用不同的对象会得到不同的状态。

基本使用:

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        print("汪汪汪")

class Cat(Animal):
    def speak(self):
        print("喵喵喵")

def make_noise(animal:Animal):
    animal.speak()

dog = Dog()
cat = Cat()

make_noise(dog) # 汪汪汪
make_noise(cat) # 喵喵喵

make_noise会根据传入的对象调用该对象的speak方法。

父类只确定有哪些方法,并不实现,具体的实现方法由子类决定,这种写法也叫做抽象类(也可称之为接口