Python面向对象编程-学习笔记

发布时间 2023-07-27 17:46:03作者: 尼古拉-卡什

课程地址: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)
#另一种调用类中方法的方式