Python: retrieve all properties of a class instance that uses the @property annotation
-
27-10-2019 - |
سؤال
Is there an easy way to retrieve all properties of a class instance that use @property or property methods?
I have seen examples that use vars but that does not work a class like:
class Test(object):
CONSTANT='SKIP ME'
def __init__(self):
self.my = "my"
self.__wrapper = {Test.CONSTANT : "wrapped value"}
@property
def wrapped_value(self):
return self.__wrapper[Test.CONSTANT]
Desired output would be dictionary with key/value.
dict = {"my": "my",
"wrapped_value": "wrapped value",
"__wrapper" : <dict>
}
As an added plus is there a way to get it to skip class level variables?
المحلول
A simple solution would be this:
instance = Test()
dict((p, getattr(instance, p))
for p in dir(instance)
if p not in dir(Test) or isinstance(getattr(Test, p), property))
It yields:
{'_Test__wrapper': {'SKIP ME': 'wrapped value'}, 'wrapped_value': 'wrapped value', 'my': 'my'}
نصائح أخرى
property
is a class. Just test the class members to see if they're an instance of it.
>>> class Foo(object):
... @property
... def bar(self):
... return self._bar
...
>>> [x for x in Foo.__dict__ if isinstance(Foo.__dict__[x], property)]
['bar']
>>> foo = Foo()
>>> [x for x in foo.__class__.__dict__ if isinstance(foo.__class__.__dict__[x], property)]
['bar']
>>> dict((x, getattr(foo, x)) for x in foo.__class__.__dict__ if isinstance(foo.__class__.__dict__[x], property))
{'bar': 42}
This will result in a dictionary of all properties of a class instance that use @property or property methods. It's similar to what others have said.
a = Test()
propdict = {} # or propdict = dict()
for attrname in dir(a.__class__):
if isinstance(getattr(a.__class__, attrname), property):
propdict[attrname] = getattr(a, attrname)
Then propdict
would be {'wrapped_value': 'wrapped value'}
, as wrapped_value
is the only property of your Test
class.
لا تنتمي إلى StackOverflow