python如何查看类的所有属性

29次阅读
没有评论

共计 641 个字符,预计需要花费 2 分钟才能阅读完成。

在 Python 中,可以使用内置函数 dir() 来查看一个类的所有属性。dir()函数返回一个列表,包含指定对象的所有属性和方法。

例如,假设有一个名为 Person 的类,我们可以使用 dir(Person) 来查看该类的所有属性。示例如下:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello!")

# 查看 Person 类的所有属性
print(dir(Person))

输出结果为:

['__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', 'name', 'say_hello']

注意,dir()函数返回的列表中包含了类的一些特殊属性,如 __init____str__ 等。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计641字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)