如何遍历getter或@property定义的对象的属性?

问题描述 投票:0回答:2

我知道如何遍历对象的属性。但这排除了通过getter / setter或@property装饰器实现的属性。

我怎么能遍历那些?

class MyClass:

    def __init__(self):
        self.foo = "bar"

    @property
    def myprop(self):
        return "hello"


my_instance = MyClass()

for i in my_instance.__dict__:
    print("object has attribute %s" % i)

这个小脚本打印:

object has attribute foo

我想要的是打印的脚本:

object has attribute foo
object has attribute myprop
python python-3.x loops getter
2个回答
0
投票

您可以使用dir()获取所有属性,但这将包括从基类继承的方法,包括来自object的所有dunder方法:

class MyClass:

    def __init__(self):
        self.foo = "bar"

    @property
    def myprop(self):
        return "hello"


my_instance = MyClass()

for i in dir(my_instance):
    print("object has attribute %s" % i)

打印:

object has attribute __class__
object has attribute __delattr__
object has attribute __dict__
object has attribute __dir__
object has attribute __doc__
object has attribute __eq__
object has attribute __format__
object has attribute __ge__
object has attribute __getattribute__
object has attribute __gt__
object has attribute __hash__
object has attribute __init__
object has attribute __init_subclass__
object has attribute __le__
object has attribute __lt__
object has attribute __module__
object has attribute __ne__
object has attribute __new__
object has attribute __reduce__
object has attribute __reduce_ex__
object has attribute __repr__
object has attribute __setattr__
object has attribute __sizeof__
object has attribute __str__
object has attribute __subclasshook__
object has attribute __weakref__
object has attribute foo
object has attribute myprop

你可以用字符串操作排除一些:

for i in dir(my_instance):
    if i.startswith("__"):
        continue
    print("object has attribute %s" % i)

打印:

object has attribute foo
object has attribute myprop

0
投票

您可以在对象类中查找property实例:

def get_properties(obj):
    cls = type(obj)
    props = {}
    for k in dir(cls):
        attr = getattr(cls, k)
        # Check that it is a property with a getter
        if isinstance(attr, property) and attr.fget:
            val = attr.fget(obj)
            props[k] = attr.fget(obj)
    return props

class A(object):
    def __init__(self, p):
        self._p = p
    @property
    def p(self):
        return self._p
    p2 = property(fget=lambda self: 2 * self._p)

a = A(1)
a_props = get_properties(a)
print(a_props)
# {'p': 1, 'p2': 2}
© www.soinside.com 2019 - 2024. All rights reserved.