Nhập môn Lập trình Hướng đối tượng với 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 và salary là giá trị riêng cho từng đối tượngself gán cho một đối tượngclassclass Employee: # Define a class attribute # No self. syntax MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salaryelse: self.salary = Employee.MIN_SALARY
MIN_SALARY được chia sẻ giữa tất cả các phiên bảnself để định nghĩa thuộc tính lớpClassName.ATTR_NAME để truy cập giá trị thuộc tính lớpclass Employee: # Define a class attribute MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # Use class name # to access class attribute 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)# Update MIN_SALARY of emp1 emp1.MIN_SALARY = 50000# Print MIN_SALARY for both employees print(emp1.MIN_SALARY) print(emp2.MIN_SALARY)
50000
30000
MIN_SALARY được tạo trong định nghĩa lớpMIN_SALARY của một đối tượng sẽ không ảnh hưởng đến giá trị trong định nghĩa lớphost, port cho một lớp DatabaseNhập môn Lập trình Hướng đối tượng với Python