Python list all class attributes

How to Get a List of Class Attributes in Python

The other day, I was trying to figure out if there was an easy way to grab a class’s defined attributes (AKA “instance variables”). The reason was that we were using the attributes we created to match up with the fields in a file we parse. So basically we read a file line-by-line and each line can be split into 150+ pieces that need to be mapped to the fields we create in the class. The catch is that we recently added more fields to the class and there’s a check in the code that is hard-coded with the number of fields that should be in the file. Thus, when I added more fields, it broke the check. I hope that all made sense. Now you know the background, so we can move on. I found three different ways to accomplish this, so we’ll go from the most complex to the simplest.

As most Python programmers should know, Python provides a handy little builtin called dir. I can use that on a class instance to get a list of all the attributes and methods of that class along with some inherited magic methods, such as ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__format__’, etc. You can try this yourself by doing the following:

However, I don’t want the magic methods and I don’t want the methods either. I just want the attributes. To make everything crystal clear, let’s write some code!

######################################################################## class Test: """""" #---------------------------------------------------------------------- def __init__(self): self.varOne = "" self.varTwo = "" self.varThree = "" #---------------------------------------------------------------------- def methodOne(self): """""" print "You just called methodOne!" #---------------------------------------------------------------------- if __name__ == "__main__": t = Test()

What we want to get is a list that only contains self.varOne, self.varTwo and self.varThree. The first method that we will look at is using Python’s inspect module.

import inspect variables = [i for i in dir(t) if not inspect.ismethod(i)]

Doesn’t look too complicated, does it? But it requires an import and I’d prefer not to do that. On the other hand, if you need to do introspection, the inspect module is a great way to go. It’s quite powerful and can tell you lots of wonderful things about your class or one you didn’t even write. Anyway, the next easiest way that I found was to use Python’s callable builtin:

variables = [i for i in dir(t) if not callable(i)]

You can read more about callable in the Python docs. Basically all that callable does is return a True or False depending on whether or not the object you passed it is callable. Methods are callable, variables are not. Thus we loop over each item in the class dict and only append them to the list if they are not callable (i.e. not methods). Pretty slick and it doesn’t require any imports! But there’s an even easier way!

Читайте также:  Java log all http requests

The simplest way that I found was using the magic method, __dict__. This is built into every class you make unless you override it. Since we’re dealing with a Python dictionary, we can just call its keys method!

The real question now is, should you use a magic method to do this? Most Python programmer will probably frown on it. They’re magic, so they shouldn’t be used unless you’re doing metaprogramming. Personally, I think it’s perfectly acceptable for this use case. Let me know of any other methods that I’ve missed or that you think are better.

Resources

Источник

Get a List of Class Attributes in Python

Python classes are mostly templates for creating new objects. The contents/attributes of the objects belonging to a class are described by the class.

What exactly are class attributes?

Class attributes are nothing but variables of a class. It is important to note that these variables are shared between all the instances of the class.

class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z)

In the above example code, z is a class attribute and is shared by the class instances obj1 and obj2.

In this tutorial, you will learn how to fetch a list of the class attributes in Python.

Using the dir() method to find all the class attributes

It returns a list of the attributes and methods of the passed object/class. On being called upon class objects, it returns a list of names of all the valid attributes and base attributes too.

Syntax: dir(object) , where object is optional.

Here, you can obtain the list of class attributes;

Читайте также:  Parent class property php

    By passing the class itself

class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z) print(dir(example)) #By passing the class itself
5 10 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'z']
class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z) print(dir(obj1)) #By passing the object of class
5 10 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'z']

However, the dir() method also returns the magic methods of the class along with the class attributes.

By using __dict__ get class attributes

It stores/returns a dictionary of the attributes that describe an object. Let us understand the same by looking into an example.

class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(apple.name) print(apple.color) print(apple.__dict__)

Here, apple is an object belonging to class fruit. So, the __dict__ has returned a dictionary that contains the attributes of the object i.e., apple.

Also, you can further get just the keys or values for the particular object by using the dictionary’s key, value system of storage.

class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(apple.name) print(apple.color) print(apple.__dict__) print(apple.__dict__.keys()) print(apple.__dict__.values())
apple red dict_keys(['name', 'color']) dict_values(['apple', 'red'])

By using the inspect module’s getmembers()

The getmembers() function retrieves the members of an object such as a class in a list.

import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(inspect.getmembers(apple))
[('__class__', ), ('__delattr__', ), ('__dict__', ), ('__dir__', ), ('__doc__', None), ('__eq__', ), ('__format__', ), ('__ge__', ), ('__getattribute__', ), ('__gt__', ), ('__hash__', ), ('__init__', >), ('__init_subclass__', ), ('__le__', ), ('__lt__', ), ('__module__', '__main__'), ('__ne__', ), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__setattr__', ), ('__sizeof__', ), ('__str__', ), ('__subclasshook__', ), ('__weakref__', None), ('color', 'red'), ('name', 'apple')]

To get a list of just the passed object’s attribute, i.e., to remove all the public and private in-built attributes/magic methods from the list;

import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") for i in inspect.getmembers(apple): if not i[0].startswith('_'): if not inspect.ismethod(i[1]): print(i)

Using the vars() method

It takes an object as a parameter and returns its attributes.

import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(vars(apple))

However, you must observe that the above two methods return the class attributes only for the respective base class.

Читайте также:  Переименовать папку на php

Источник

How to Get a List of Class Attributes in Python

To get a list of class attributes in Python, you can use the built-in “dir()” function or the “vars()” function.

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together.

Using the “dir()” method

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get a list of all attributes and methods of obj print(dir(obj))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attribute1', 'attribute2', 'method1'] 

Using the vars() function

The vars() function returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get a dictionary of all attributes of obj print(vars(obj)) 

Using getmembers() Method

The getmembers() function from the inspect module in Python is used to get the members of an object, such as a class or module. This function returns a list of tuples, where each tuple contains the name and value of a member.

import inspect class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Get the members of MyClass members = inspect.getmembers(MyClass) # Print the members for name, value in members: print(f": ")
__class__: __delattr__: __dict__: , '__dict__': , '__weakref__': , '__doc__': None> __dir__: __doc__: None __eq__: __format__: __ge__:

Using __dict__() Magic Method

The __dict__ is a special attribute in Python that holds the namespace of the object, module, or class. This dictionary object contains all the variables (and their values) that have been defined in the object.

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get the __dict__ of obj print(obj.__dict__) 

Источник

Оцените статью