How to list all class properties
Question:
I have class SomeClass with properties. For example id
and name
:
class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
What is the easiest way to list properties? I need this for serialization.
Answers:
property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]
import inspect
def isprop(v):
return isinstance(v, property)
propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]
inspect.getmembers
gets inherited members as well (and selects members by a predicate, here we coded isprop
because it’s not among the many predefined ones in module inspect
; you could also use a lambda
, of course, if you prefer).
I have class SomeClass with properties. For example id
and name
:
class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
What is the easiest way to list properties? I need this for serialization.
property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]
import inspect
def isprop(v):
return isinstance(v, property)
propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]
inspect.getmembers
gets inherited members as well (and selects members by a predicate, here we coded isprop
because it’s not among the many predefined ones in module inspect
; you could also use a lambda
, of course, if you prefer).