Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Truy cập thuộc tính và phương thức trong Python


Python OOP: Class là bản thiết kế, Instance (object) được tạo từ class. Truy cập attribute/method qua built-in functions.

1. Truy cập attribute của CLASS (không cần instance)

class StateInfo:
    StateName = 'Telangana'
    population = '3.5 crore'
    def func1(self):
        print("Hello from my function")

# getattr - lấy giá trị attribute (có default)
print(getattr(StateInfo, 'StateName'))           # Telangana
print(getattr(StateInfo, 'non_exist', 'N/A'))    # N/A (không lỗi)

# hasattr - kiểm tra tồn tại
print(hasattr(StateInfo, 'population'))  # True

# setattr - đặt/gán attribute mới
setattr(StateInfo, 'ForestCover', 39)
print(getattr(StateInfo, 'ForestCover'))  # 39

# Kiểm tra method cũng là attribute
print(hasattr(StateInfo, 'func1'))  # True

2. Truy cập method qua INSTANCE

obj = StateInfo()
obj.func1()  # Hello from my function

# Hoặc qua getattr
method = getattr(obj, 'func1')
method()

3. Gọi method của class A từ class B

class ClassOne:
    def m_class1(self):
        print("Method in class 1")

class ClassTwo:
    def __init__(self, cls_one):
        self.cls_one = cls_one  # Nhận class (không phải instance)

    def m_class2(self):
        instance = self.cls_one()  # Tạo instance
        instance.m_class1()

# Sử dụng
obj = ClassTwo(ClassOne)
obj.m_class2()  # Method in class 1

Lưu ý

  • getattr/setattr/hasattr hoạt động trên cả class và instance.
  • Method thực chất là function attribute của class, bound method khi truy cập qua instance.
  • Để gọi method của class khác: truyền class hoặc instance vào.

Kết luận

Python cung cấp reflection mạnh mẽ: getattr, setattr, hasattr, delattr cho metaprogramming, plugin, serialization.