可以使用 dir() 函数来获取一个类的所有属性和方法,例如:

class MyClass:
    def __init__(self):
        self.name = 'John'
        self.age = 30

    def say_hello(self):
        print('Hello, my name is', self.name)

print(dir(MyClass))

输出:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'say_hello']

可以看到,输出包含了类的所有属性和方法,包括 agesay_hello。需要注意的是,dir() 函数也会输出一些特殊的属性和方法,例如 __init____class__ 等,这些是 Python 内置的特殊属性和方法。

Python 获取类属性和方法:使用 dir() 函数

原文地址: https://www.cveoy.top/t/topic/jqDp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录