Reputation: 341
Dear Stackoverflow community,
I am trying to get a list of properties in my class. So far I have this:
class A(object):
def __init__(self):
self._val = 0
@property
def val(self):
return self._val
@val.setter
def val(self, val):
"""
+1 just as a lazy check if the method is invoked
"""
self._val = val + 1
def get_props(self):
return [ str(x) for x in dir(self)
if isinstance( getattr(self, x), property ) ]
if __name__ == "__main__":
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
print()
a = A()
print(f"Before asigment: {a.val}")
a.val = 19
print(f"After asigment: {a.val}")
print(f"My properties: {a.get_props()}")
print(f"The type of the attribute 'val' is {type(getattr(a, 'val'))}")
According to this Q/A it should work. However, my result is:
Python version
3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0]
Version info.
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)
Before asigment: 0
After asigment: 20
My properties: []
The type of the attribute 'val' is <class 'int'>
I'm trying to avoid importing new modules (like inspect). What am I missing?
Thank you!
Upvotes: 0
Views: 1631
Reputation: 10452
property
s are defined on the class, if you try to access them via an instance, their __get__
is called. So make it a class method instead:
@classmethod
def get_props(cls):
return [x for x in dir(cls)
if isinstance( getattr(cls, x), property) ]
Upvotes: 5