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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With