Python 面向对象编程入门
George Boorman
Curriculum Manager, DataCamp
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("Teo Mille", 50000)
emp2 = Employee("Marta Popov", 65000)
name 与 salary 的值对每个对象各不相同self 将值赋给对象自身
class 体内定义"类属性"
class Employee: # 定义类属性 # 无 self. 语法 MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # 使用类名 # 访问类属性 if salary >= Employee.MIN_SALARY: self.salary = salaryelse: self.salary = Employee.MIN_SALARY
MIN_SALARY 在所有实例间共享selfClassName.ATTR_NAME 访问类属性值class Employee: # 定义类属性 MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # 使用类名 # 访问类属性 if salary >= Employee.MIN_SALARY: self.salary = salary else: self.salary = Employee.MIN_SALARY
emp1 = Employee("John", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("Jane", 60000)
print(emp2.MIN_SALARY)
30000
emp1 = Employee("John", 40000) emp2 = Employee("Jane", 60000)# 更新 emp1 的 MIN_SALARY emp1.MIN_SALARY = 50000# 分别打印两位员工的 MIN_SALARY print(emp1.MIN_SALARY) print(emp2.MIN_SALARY)
50000
30000
MIN_SALARY 在类定义中创建
MIN_SALARY 不会影响类定义中的值
Database 类的 host、portPython 面向对象编程入门