Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of attributes in class

Tags:

python

How would I get a list of attributes in a class? For example:

class Test:
    def __init__(self,**kw):
        for k,v in kw.items():
            setattr(self,k,v)
x = Test(value="hello",valueTwo="world")
print(dir(x))

I've done that and it seems to print the keys but, it also prints extra stuff like:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__','value','valueTwo']

is there another way to do this so it just gets the keys/values.

like image 818
user2925490 Avatar asked Oct 27 '13 16:10

user2925490


People also ask

How do I get all attributes of a class?

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 .

How do I get attributes in Python?

Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

How do I see all the attributes of an object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.


1 Answers

Use x.__dict__:

>>> x.__dict__
{'value': 'hello', 'valueTwo': 'world'}

>>> [ v for k,v in x.__dict__.items() if '__' not in k and 'object at' not in k ]
like image 111
Ashwini Chaudhary Avatar answered Oct 28 '22 14:10

Ashwini Chaudhary