Skip to main content
 首页 » 编程设计

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

2024年11月24日8think

我想像这样使用自定义描述符进行验证和(反)序列化:

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 的所有属性(例如 foo 和 bar),而不是其他(例如 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 

如何列出按 Descriptor 类型过滤的对象属性?

更新:

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

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

请您参考如下方法:

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

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

这个输出:

foo 
bar