列出对象的属性

2024-03-28 09:57:01 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有方法获取类实例上存在的属性列表?

class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))

期望的结果是输出“multi,str”。我希望看到脚本各个部分的当前属性。


Tags: 实例方法selfnumber列表new属性init
3条回答

vars(obj)返回对象的属性。

>>> class new_class():
...   def __init__(self, number):
...     self.multi = int(number) * 2
...     self.str = str(number)
... 
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])

你也会发现pprint很有帮助。

dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__

然后您可以使用type()测试什么类型,或者使用callable()测试是否是方法。

相关问题 更多 >