如何在python中获取对象的属性

2024-09-29 23:23:02 发布

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

class ClassB:
    def __init__(self):
        self.b = "b"
        self.__b = "__b"

    @property
    def propertyB(self):
        return "B"

我知道getattr,hasattr...可以访问属性。 但是为什么没有iterattrlistattr?你知道吗

ClassB对象的预期结果:

{'propertyB': 'B'}

ClassB类的预期结果:

['propertyB']

谢谢@胡安帕.阿里维拉加的评论。 vars(obj)vars(obj.__class__)是不同的!你知道吗


Tags: selfobjreturn属性initdefpropertyvars
2条回答

要列出python类的属性,可以使用dict

示例

>>> class C(object):
x = 4

>>> c = C()
>>> c.y = 5
>>> c.__dict__
{'y': 5}

有关更多示例和信息,请参见此链接-https://codesachin.wordpress.com/2016/06/09/the-magic-behind-attribute-access-in-python/

使用内置的^{}如下所示:

properties = []
for k,v in vars(ClassB).items():
    if type(v) is property:
        properties.append(k)

使用列表理解:

>>> [k for k,v in vars(ClassB).items() if type(v) is property]
['propertyB']

相关问题 更多 >

    热门问题