Trung BìnhPython iconPython

`@classmethod` vs `@staticmethod` vs instance method?

Instance method nhận self — có access vào instance và class. @classmethod nhận cls — access class, thường dùng làm factory. @staticmethod không nhận self hay cls — utility function liên quan đến class.

python
class User:
    _count = 0

    def __init__(self, name):
        self.name = name
        User._count += 1

    def greet(self):            # Instance method
        return f"Hi, {self.name}"

    @classmethod
    def from_dict(cls, data):   # Factory — dùng cls thay vì User
        return cls(data['name'])

    @staticmethod
    def validate_name(name):    # Utility — không cần self/cls
        return len(name) >= 2

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python