简体   繁体   English

如何在python中获取类的所有属性

[英]How to get all the properties of a class in python

I have this class in python defined like this 我在python中定义了这样的课程

class MyClass(object):
   @property
   def property1(self):
       # type: () -> pb.data.Property1

   @property
   def property2(self):
       # type: () -> pb.data.Property2

How can I use reflection to read all the properties that the class has and then make a map from the property name to its class 如何使用反射读取类具有的所有属性,然后从属性名称映射到其类

something like 就像是

{"property1":"pb.data.Property1", "property2":"pb.data.Property2"}

Remember that the first line in each property is a comment. 请记住,每个属性的第一行都是注释。 Is there a clear way to do it? 有明确的方法吗?

You can use inspect.getmembers to get all the attribute values. 您可以使用inspect.getmembers获取所有属性值。 Hopefully below code will help you out. 希望下面的代码能对您有所帮助。

import inspect
class MyClass(object):
    @property
    def property1(self):
        return 'pb.data.Property1'

    @property
    def property2(self):
        return 'pb.data.Property2'

    def get_attributes(self):
        attributes = inspect.getmembers(self, predicate=lambda a: not(inspect.isroutine(a)))
        return {d[0]:d[1] for d in attributes if not(d[0].startswith('__') and d[0].endswith('__'))}


MyClass().get_attributes()

Output : {'property1': 'pb.data.Property1', 'property2': 'pb.data.Property2'} 输出{'property1': 'pb.data.Property1', 'property2': 'pb.data.Property2'}

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

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