【问题标题】:Listing object attributes filtered by Descriptor type列出按描述符类型过滤的对象属性
【发布时间】:2019-09-03 06:29:18
【问题描述】:

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

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),但不返回其他属性(例如 baz)。在阅读Iterate over object attributes in python 之后,这是我到目前为止所尝试的:

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

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

更新:

基于accepted answer(谢谢!),我最终得到了这个:

def list_my_properties (self):
    return [ field for field, value in self.__class__.__dict__.items()
            if isinstance(value, MyProperty) ]

【问题讨论】:

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


    【解决方案1】:

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

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

    这个输出:

    foo
    bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 2016-02-26
      • 1970-01-01
      相关资源
      最近更新 更多