Python中类的继承
类的继承特点:
1. 如果类中不定义__init__,调用父类__init__
2. 如果类继承父类也需要定义自己的__init__,就需要在当前类的__init__调用一下父类的__init__
3. 如果调用父类__init__:
super().__init__(参数)
super(类名,对象).__init__(参数)
4. 如果父类有eat(),子类也定义一个eat()方法,默认搜索的原则:先找当前类,再去找父类
s.eat()
override:重写(覆盖)父类方法
父类提供的方法不能满足子类的需求,就需要在子类中定义一个同名的方法,即重写方法
5. 子类的方法中也可以调用父类的方法: super().方法名(参数)
# 父类
class Person:
def __init__(self, name, age, occupation):
self.__name = name
self.__age = age
self.__occupation = occupation
def eat(self):
print(self.__name + '正在吃饭...')
def run(self):
print(self.__name + '正在跑步...')
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
@property
def occupation(self):
return self.__occupation
@occupation.setter
def occupation(self, occupation):
self.__occupation = occupation
# 子类1
class Student(Person):
# 在重写子类的init之前先要调用父类的init
def __init__(self, name, age, occupation, clazz):
print('-----------Student的init')
# 调用父类的init
super().__init__(name, age, occupation) # 使用super() 调用父类对象
self.__clazz = clazz
def study(self, course):
print('{}正在学习{}'.format(self.name, course))
def __str__(self):
return '姓名:{},年龄:{},身份:{},班级:{}'.format(self.name, self.age, self.occupation, self.__clazz)
# 子类2
class Employee(Person):
def __init__(self, name, age, occupation, salary, manager):
super().__init__(name, age, occupation) #
self.__salary = salary
self.__manager = manager
self.__occupation = occupation
def __str__(self):
return '姓名:{},年龄:{},身份:{},薪资:{},领导:{}'.format(self.name, self.age, self.__occupation, self.__salary,
self.__manager)
s = Student('张三', 18, '学生', '2019学习班')
print(s)
s.run()
s.study('python')
e = Employee('李四', 30, '职员', 8000, '总经理')
print(e)
e.eat()
------学习贵在分享,贵在记录,贵在总结。