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

Làm thế nào để liệt kê các phương thức của một lớp Python?

Để lấy danh sách các phương thức của một lớp trong Python, bạn có thể sử dụng module inspect kết hợp với hàm getmembers() và predicate inspect.ismethod (hoặc inspect.isfunction tùy phiên bản Python).

Ví dụ

class Foo:
    def __init__(self):
        self.x = 10
    def bar(self):
        pass
    def baz(self):
        pass

import inspect
# Lấy các phương thức unbound (Python 2) hoặc function (Python 3)
print(inspect.getmembers(Foo, predicate=inspect.isfunction))
# Hoặc nếu muốn bao gồm cả method đã bind
print(inspect.getmembers(Foo, predicate=inspect.ismethod))

Kết quả (Python 3)

[('__init__', ), ('bar', ), ('baz', )]

Lưu ý: Trong Python 3, các phương thức trong class được coi là function (chưa bind), còn instance.method thì là method. Sử dụng inspect.isfunction cho class, inspect.ismethod cho instance.