解决代码冗余的问题,提高效率
可以创建有层次的类
子类和父类 -- 和遗传学上的父子一样
先写父类
子类:class 子类名(父类名):
xxx
子类如果没有自己的构造函数,就会调用父类的构造函数
优先看所属的类有没有该方法
若无,向上找父类的同名方法来用
注:若子类中有init方法,则创建子类实例时,优先调用子类的构造函数,会导致实例中没有父类属性
解决方法:用super
例:
class Mammal:
def __init__(self, name, sex):
self.name = name
self.sex = sex
self.num_eyes = 2
def breathe(self):
print(self.name + "会呼吸")
def poop(self):
print(self.name + "会上厕所")
#子类
class Human(Mammal):
def __init__(self,name,sex):
#返回当前类的父类
super().__init__(name,sex)
self.has_tail = False
def read(self):
print(self.name + "在阅读")
#子类
class Cat(Mammal):
def __init__(self, name, sex):
super().__init__(name,sex)
self.has_tail = True
cat1 = Cat("a","male")
print(cat1.name)
cat1.poop()
若A与B,若A是B,则可以把A写成B的子类
class A(B)
员工分为两类:全职和兼职
全职和兼职都有姓名和工号属性,都具备打印信息(姓名和工号)方法
全职有月薪属性
兼职有日薪和每月工作天数的属性
全职和兼职都有计算月薪的方法,但具体计算过程不同
#父类
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def print_info(self):
print(f"该员工姓名为{self.name},工号为:{self.id}")
#子类
class FullEmployee(Employee):
def __init__(self, name, id, monthly_salary):
super().__init__(name, id)
self.monthly_salary = monthly_salary
def cal_salary(self):
print(f"全职员工{self.name}的月薪为{self.monthly_salary}")
class PartEmployee(Employee):
def __init__(self, name, id, daily_salary, work_day):
super().__init__(name, id)
self.daily_salary = daily_salary
self.work_day = work_day
def cal_salary(self):
monthly_part = int(self.daily_salary) * int(self.work_day)
print(f"兼职员工{self.name}的月薪为{monthly_part}")
#测试功能
people1 = FullEmployee("ZHANG", "4521", "10000")
print(people1.name)
people1.print_info()
people1.cal_salary()
people2 = PartEmployee("wang", "4522", "150", "20")
people2.print_info()
people2.cal_salary()
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def print_info(self):
print(f"该员工姓名为{self.name},工号为:{self.id}")
class FullEmployee(Employee):
def __init__(self, name, id, monthly_salary):
super().__init__(name, id)
self.monthly_salary = monthly_salary
def cal_salary(self):
return self.monthly_salary
class PartEmployee(Employee):
def __init__(self, name, id, daily_salary, work_day):
super().__init__(name, id)
self.daily_salary = daily_salary
self.work_day = work_day
def cal_salary(self):
return int(self.daily_salary) * int(self.work_day)