类的继承:
一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类 ,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
创建子类时,必须在括号内指定父类的名称。子类和父类可以不再同一个py文件中。
继承关系中,父类的__init__方法不会被自动调用,如果需要,必须在子类中明确调用它。
例子1:
在test20240117.py文件中:
class Dog():
pet_shop = '萌宠小屋'
def __init__(self, name, age):
self.name = name
self.age = age
#坐def sit(self):
print(self.name.title() + " is now sitting.")
#打滚def roll_over(self):
print(self.name.title() + " rolled over!")
def _say_hi(self):
print("say hi!")
在test20240307.py文件中:
import test20240117 as test
class Dog2(test.Dog):
def __init__(self):
pass
def sit(self):
print("子类sit")
dog2 = Dog2()
dog2.sit()
结果:
"C:\Program Files\Python312\python.exe" D:/pythonProject/test/test20240307.py
子类sit
重写父类的方法
在子类中定义一个方法,和父类的方法同名,子类中的方法将覆盖父类中方法。
class Animal():
pet_shop = '萌宠小屋'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print("say hi!")
class Dog(Animal):
pet_shop = '汪汪队'
def __init__(self, name, age):
self.name = name
self.age = age
#坐def sit(self):
print(self.name.title() + " is now sitting.")
#打滚def roll_over(self):
print(self.name.title() + " rolled over!")
def say_hi(self):
print("wang wang!")
animal = Animal('动物',2)
animal.say_hi()
dog = Dog('狗子',3)
dog.say_hi()
结果:
say hi!
wang wang!
例子:多重继承,按照在在子类定义时,括号中的顺序继承,同名的优先继承排在前面的类中的方法。
class Animal():
pet_shop = '萌宠小屋'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print("say hi!")
def say_ok(self):
print("animal say ok!")
class livestock():
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print("家畜!")
def eat(self):
print('家畜吃饭!')
def say_ok(self):
print("livestock say ok!")
class Dog(Animal,livestock):
pet_shop = '汪汪队'
def __init__(self, name, age):
self.name = name
self.age = age
#坐def sit(self):
print(self.name.title() + " is now sitting.")
#打滚def roll_over(self):
print(self.name.title() + " rolled over!")
def say_hi(self):
print("wang wang!")
animal = Animal('动物',2)
animal.say_hi()
dog = Dog('狗子',3)
dog.say_hi()
dog.eat()
dog.say_ok()
结果:
say hi!
wang wang!
家畜吃饭!
animal say ok!
在子类中调用父类的方法,使用super()关键字。
例子:
class Animal():
pet_shop = '萌宠小屋'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print("Animal say hi!")
def say_ok(self):
print("animal say ok!")
class Dog(Animal):
pet_shop = '汪汪队'
def __init__(self, name, age,sex):
super().__init__(name, age)
#坐def sit(self):
super().say_hi()
print(self.name.title() + " is now sitting.")
#打滚def roll_over(self):
print(self.name.title() + " rolled over!")
def say_hi(self):
print("wang wang!")
dog = Dog('旺财',5,'female')
dog.sit()
结果:
Animal say hi!
旺财 is now sitting.