Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all class properties

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.

like image 334
tefozi Avatar asked Jul 31 '09 23:07

tefozi


People also ask

How do you list all of the properties of a class in Python?

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 .

What are C# class properties?

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.

What is the properties of a class?

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.


2 Answers

property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)] 
like image 196
Mark Roddy Avatar answered Oct 07 '22 17:10

Mark Roddy


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).

like image 29
Alex Martelli Avatar answered Oct 07 '22 16:10

Alex Martelli