面向对象的理解可参考:2分钟让你明白什么是面向对象编程 - 知乎 (zhihu.com)
1. class
名字使用大写字母分割:
定义属性和行为
class CyberPunk: # 定义类
def __init__(self, punk_name, punk_gender, punk_status): # 属性构造函数
self.name = punk_name
self.gender = punk_gender
self.status = punk_status
def speak(self, content): # 方法构造函数(定义对象可以做的事情) 可以理解为定义一个函数
print("V said %s" % content)
character1 = CyberPunk("V", "man", "legends")
character2 = CyberPunk("Judy", "woman", "V_love")
print("%s的性别是%s,地位是%s" % (character2.name, character2.gender, character2.status))
character1.speak("fuck you")
2. 继承的运用
# 人力系统
# 员工分为两类:全职员工FulltimeEmployee和兼职员工Parttimeemployee
# 均有姓名(name)和工号(id)属性
# 都具备打印信息方法(print_info)打印姓名和工号方法
# 全职有月薪(monthly_salary)属性
# 兼职有日薪(daily_salary)属性和每月工作天数(work_days)属性
# 全职和兼职都有计算月薪的方法calculate_monthly_pay,具体计算过程不同
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def print_info(self):
print("姓名是%s,工号是%s" % (self.name, self.id))
class FulltimeEmployee(Employee):
def __init__(self, name, id, monthly_salary):
super().__init__(name, id)
self.monthly_salary = monthly_salary
def calculate_monthly_pay(self):
pay = self.monthly_salary
return pay
class ParttimeEmployee(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 calculate_monthly_pay(self):
pay = self.daily_salary * self.work_day
return pay
Alan=FulltimeEmployee("Alan","2021141410130",8000)
Judy=ParttimeEmployee("Judy","2021141410136",300,20)
Alan.print_info()
Judy.print_info()
print(Alan.monthly_salary)
print("Alan本月的工资是%d"%Alan.calculate_monthly_pay())
print("Judy本月的工资是%d"%Judy.calculate_monthly_pay())