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.
Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir() . Method 2: Another way of finding a list of attributes is by using the module inspect .
Property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, C# properties are special methods called accessors. A C# property have two accessors, get property accessor and set property accessor.
The collection of properties assigned to a class defines the class. A class can have multiple properties. For example, objects classified as computers have the following properties: Hardware ID, Manufacturer, Model, and Serial Number.
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).
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