I have this class in python defined like this
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. 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'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.