可以使用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中怎么获取类的所有的属性和方法

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

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