[英]How to get values of all properties (except inherited ones) that belong to specific class in Python 3
[英]How to get all the properties of a class in python
我在python中定義了這樣的課程
class MyClass(object):
@property
def property1(self):
# type: () -> pb.data.Property1
@property
def property2(self):
# type: () -> pb.data.Property2
如何使用反射讀取類具有的所有屬性,然后從屬性名稱映射到其類
就像是
{"property1":"pb.data.Property1", "property2":"pb.data.Property2"}
請記住,每個屬性的第一行都是注釋。 有明確的方法嗎?
您可以使用inspect.getmembers獲取所有屬性值。 希望下面的代碼能對您有所幫助。
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()
輸出 : {'property1': 'pb.data.Property1', 'property2': 'pb.data.Property2'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.