Python面向对象编程-学习笔记
课程地址:https://www.bilibili.com/video/BV1qm4y1L7y1/
1. Pass占位符,新建类后如果暂时不确定如何实现,可用pass占位
2.构造函数,属性
# Python Object-Oriented Programming class Employee: def __init__(self, first, last, pay):
#构造函数,第一个参数必须是self self.first= first
#新添加属性 self.last = last self.pay=pay self.email = first +'.'+ last+'@company.com
def GetFullName(self):
#此处必须传入self参数,表示需要引用实例化对象
#否则在调用该方法(①)时会引发"GetFullName takes 0 posional arguments but 1 was given"
#这是因为调用类的实例的方法时,实例会被自动传递到方法中,如果方法没有self则会报错
return '{} {}'.format(self.first,self.last)
emp_1 = Employee('Corey','Schafer', 50000) emp_2 = Employee('Test','User', 60000) # print(emp_1) # print(emp_2) print(emp_1.email) print(emp_2.email)
print('{} {}'.format(emp_1.first,emp_1.last))
#一种字符串格式化方法
print(emp_2.GetFullName())①
Employee.GetFullName(emp_1)
#另一种调用类中方法的方式
3.类的变量
1 class Employee: 2 raise_amount =1.04
num_of_emps=0
#定义类的变量 3 def __init__(self, first, last, pay): 4 self.first = first 5 self.last = last 6 self.pay= pay 7 self.email = first + '.' + last + '@company.com'
Employee.num_of_emps+=1
#此处不能用self,因为属于整个类,而非某个实例 8 def fullname(self): 9 return '{} {}'.format(self.first, self.last) 10 def apply_raise(self): 11 self.pay = int(self.pay * Employee.raise_ amount)
#类的变量的调用需要引用类名,否则报错未定义raise_amount
#self.pay = int(self.pay * self.raise_amount)#另一种写法
12
print(Employee.num_of_emps) #值为0 13 emp_1=Employee('Corey','Schafer', 50000) 14 emp_2= Employee('Test','User', 60000) 15 print(emp_1.pay)
print(Employee.num_of_emps) #值为2
print(emp_1.__dict__) #打印实例的属性字典,不包含raise_amount变量
print(Employee.__dict__) #打印类的属性字典,包含raise_amount变量
emp_1.raise_amount =1.05 #只影响emp_1实例
Employee.raise_amount=1.06 #影响所有实例