Animal包含Dog类,Animal是父类,Dog是Animal的子类
1 继承:一个类可以继承另一个类的所有属性和方法。
2 方法重写:如果父类和子类有相同的方法和属性,先调用子类的
class Animal:
def run(self):
print("animal running~")
class Dog(Animal):
def run(self):
print("dog running~")
your_dog = Dog()
your_dog.run()
3 多重继承:有多个类的继承关系
class Bad:
def like(self):
print("拆家~")
class Erha(Dog, Bad):
pass
his_dog = Erha()
his_dog.run()
his_dog.like()
4 获取继承的优先调用顺序
print(Erha.__mro__)
5 super():子类方法想要调用父类的任何方法,这种继承叫做超继承
class Animal:
def __init__(self, ke, color):
self.ke = ke
self.color = color
def run(self):
print("animal run")
def eat(self):
print("animal eat")
class Dog(Animal):
def __init__(self, color, kind):
# 调用父类初始化函数,然后再定义自己的特征
# self.color = color
super().__init__("dog", color)
self.kind = kind
def run(self):
super().run()
print("dog run")
super().eat()
self.eat()
his_dog = Dog("白色","阿拉斯加")
print(his_dog.ke)
print(his_dog.color)
his_dog.run()
6 getattr() 获取某个属性,如果属性不存在会返回默认值,没有默认值则报错
class Dog:
def __init__(self, color):
self.color = color
self.ke = "dog"
dog = Dog("red")
用户自己控制获取哪个属性
data = getattr(dog,"color")
print(data)
user_input = input("请输入想要获取的属性: ")
data = getattr(dog, user_input, "NO")
print(data)
7 serattr() 设置某个属性
setattr(dog, "gender", "女")
print(dog.gender)