列出按描述符类型过滤的对象属性

时间:2019-04-12 13:16:16

标签: python python-3.x properties attributes iteration

我想使用自定义描述符进行验证和反序列化,如下所示:

class MyProperty():
  def __init__ (self, **kwargs):
    self.value = None

  def __get__ (self, obj, owner_class):
    return self.value

class MyClass():
  foo = MyProperty()
  bar = MyProperty()

  def __init__(self):
    self.baz = True

  def list_my_properties(self):
    pass # TODO

我写list_my_properties失败,无法返回声明为MyProperty的所有属性(例如foobar),而不返回其他属性(例如{{1 }})。读完Iterate over object attributes in python之后,这是我到目前为止尝试过的:

baz

如何列出按描述符类型过滤的对象属性?

更新

基于accepted answer(谢谢!),我得出以下结论:

for a, v in self.__dict__.items():
  print(a, isinstance(v, MyProperty))
# [no output]

for a in dir(self):
  print(a, isinstance(getattr(self, a), MyProperty))
# foo False
# bar False
# baz False

1 个答案:

答案 0 :(得分:1)

foobar被定义为类变量,因此不会在实例的__dict__中找到它们,而是在实例的类__dict__中找到它们:

for a, v in self.__class__.__dict__.items():
    if isinstance(v, MyProperty):
        print(a)

这将输出:

foo
bar