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

时间:2019-03-26 12:20:27

标签: python python-3.x loops getter

我知道如何遍历对象的属性。但这不包括通过getters / 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

2 个答案:

答案 0 :(得分:0)

您可以使用dir()获取所有属性,尽管这将包括从基类继承的方法,包括对象的所有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

答案 1 :(得分: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}