Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ
George Boorman
Curriculum Manager, DataCamp
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def give_raise(self, amount): self.salary += amount# Unique attribute values emp_one = Employee("John", 40000)emp_one.give_raise(5000) print(emp_one.salary)
45000
# Unique attribute values emp_two = Employee("Jane", 60000)emp_two.give_raise(5000) print(emp_two.salary)
65000
class MyClass: # Use a decorator to declare a class method @classmethod# cls argument refers to the class def my_awesome_method(cls, args...): # Do stuff here # Can't use any instance attributes# Call the class, not the object MyClass.my_awesome_method(args...)
self คำว่า cls เป็นเพียงชื่อที่นิยมใช้ แต่จะใช้คำใดก็ได้class Employee: def __init__(self, name, salary): self.name = name self.salary = salary@classmethod def from_file(cls, filename): with open(filename, "r") as f: # Read the first line name = f.readline().strip() # Read the second line as integer salary = int(f.readline().strip())return cls(name, salary)
__init__() ได้เพียงตัวเดียว
return เพื่อคืนค่าอ็อบเจกต์cls(...) จะเรียกใช้ __init__(...)class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline().strip()
salary = int(f.readline().strip())
return cls(name, salary)

# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Constructor ทางเลือก
เมธอดที่ไม่จำเป็นต้องใช้แอตทริบิวต์ระดับอินสแตนซ์
การจำกัดให้มีอินสแตนซ์ (อ็อบเจกต์) เดียวของคลาส
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ