简体   繁体   English

如何获取 object 的所有属性及其子对象的属性?

[英]How to get all attributes of an object and the attributes of its subobjects?

How to use a pythonic way to get all attribute of instance f and get do the same to just obtained attribute.如何使用 pythonic 方式获取实例f的所有属性并对刚刚获得的属性执行相同的操作。

I want to get ['__init__', 'own', 'Meta', 'field'] , no matter the order.我想得到['__init__', 'own', 'Meta', 'field'] ,无论顺序如何。

class Foo:
    def __init__(self) -> None:
        self.own = 'own'

    class Meta:
        field = None


f = Foo()
print(dir(f))

I want to get all attributes of f and the attributes of its subobjects.

if specific_attr in attrs:
    do_something

When i use dir(f) , i got too much value, filtering from this seems a bit troublesome and there is no attribute 'field' , i need to use dir(f.Meta) again.当我使用dir(f)时,我得到了太多的价值,从中过滤似乎有点麻烦,并且没有attribute 'field' ,我需要再次使用dir(f.Meta)

I want an easy way to get all attributes of instance f and the attributes of its subobjects, my purpose is:我想要一种简单的方法来获取实例f的所有属性及其子对象的属性,我的目的是:

if specific_attr in attrs: do_something

Try尝试

print(dir(Foo))

This should give you the list of properties you want.这应该为您提供所需的属性列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM