Các Loại Phương Thức Trong Lớp Python
· 2 min read
🔹 1. Instance Methods – Phương thức của đối tượng
class Stock:
def __init__(self, name, price):
self.name = name
self.price = price
def update_price(self, new_price):
self.price = new_price
print(f"Giá cổ phiếu {self.name} đã cập nhật: {self.price}")
s = Stock("AAPL", 175)
s.update_price(180)
🔹 2. Class Methods – Phương thức của lớp
class Stock:
stock_count = 0
def __init__(self, name, price):
self.name = name
self.price = price
Stock.stock_count += 1
@classmethod
def get_stock_count(cls):
return cls.stock_count
s1 = Stock("AAPL", 175)
s2 = Stock("TSLA", 720)
print("Tổng số cổ phiếu:", Stock.get_stock_count())
🔹 3. Static Methods – Phương thức tĩnh
class Stock:
@staticmethod
def is_trading_hour(hour):
return 9 <= hour <= 16
print(Stock.is_trading_hour(14)) # True
print(Stock.is_trading_hour(20)) # False
🔹 4. Dunder Methods – Phương thức đặc biệt
class Stock:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"Cổ phiếu {self.name} có giá {self.price}"
def __repr__(self):
return f"Stock('{self.name}', {self.price})"
s = Stock("AAPL", 175)
print(s) # __str__()
print(repr(s)) # __repr__()
📌 Tổng kết
Loại phương thức | Decorator | Dùng để làm gì? |
---|---|---|
Instance Method | Không có | Làm việc với từng đối tượng |
Class Method | @classmethod | Làm việc với lớp (dùng cls ) |
Static Method | @staticmethod | Hàm thông thường trong lớp |
Dunder Method | __init__ , __str__ , __add__ ... | Tùy chỉnh hành vi |