To add to the John La Rooy's answer (and bugmenot123's comment), it's easy to extend the code to check for arbirary attribute names.
Let's define a class with a property, and its instance:
class MyClass:
not_a_property = None
@property
def my_property(self):
pass
def my_method(self):
pass
my_object = MyClass()
We can simply use any getattr
with an arbitrary string to check if the attribute of the class of the given object is a property, just like John La Rooy demonstrated:
>>> isinstance(getattr(type(my_object), 'not_a_property'), property)
False
>>> isinstance(getattr(type(my_object), 'my_property'), property)
True
>>> isinstance(getattr(type(my_object), 'my_method'), property)
False
To get for all property method names of an object, you can loop through dir
of the class, like this:
for attr in dir(type(my_object)):
print(
f'{attr} is a property method:'.ljust(42),
isinstance(getattr(type(my_object), attr), property)
)
The loop above prints the following output:
__class__ is a property method: False
__delattr__ is a property method: False
__dict__ is a property method: False
__dir__ is a property method: False
__doc__ is a property method: False
__eq__ is a property method: False
__format__ is a property method: False
__ge__ is a property method: False
__getattribute__ is a property method: False
__gt__ is a property method: False
__hash__ is a property method: False
__init__ is a property method: False
__init_subclass__ is a property method: False
__le__ is a property method: False
__lt__ is a property method: False
__module__ is a property method: False
__ne__ is a property method: False
__new__ is a property method: False
__reduce__ is a property method: False
__reduce_ex__ is a property method: False
__repr__ is a property method: False
__setattr__ is a property method: False
__sizeof__ is a property method: False
__str__ is a property method: False
__subclasshook__ is a property method: False
__weakref__ is a property method: False
my_method is a property method: False
my_property is a property method: True
not_a_property is a property method: False