- Get a List of Class Attributes in Python
- Using the dir() method to find all the class attributes
- By using __dict__ get class attributes
- By using the inspect module’s getmembers()
- Using the vars() method
- How to list all fields of a class (and no methods)?
- Similar question
- Related Query
- More Query from same tag
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;
- 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.
How to list all fields of a class (and no methods)?
You can get it via the __dict__ attribute, or the built-in vars function, which is just a shortcut:
>>> class A(object): . foobar = 42 . def __init__(self): . self.foo = 'baz' . self.bar = 3 . def method(self, arg): . return True . >>> a = A() >>> a.__dict__ >>> vars(a)
There’s only attributes of the object. Methods and class attributes aren’t present.
Maxime Lorant 32686
Similar question
You can iterate through an instance’s __dict__ attribute and look for non-method things. For example:
CALLABLES = types.FunctionType, types.MethodType for key, value in A().__dict__.items(): if not isinstance(value, CALLABLES): print(key)
You can do it in a single statement with a list comprehension:
print(Python get all fields in class)
Which would print [‘foo’, ‘bar’] .
martineau 115235
This should work for callables:
[f for f in dir(o) if not callable(getattr(o,f))]
You could get rid of the rest with:
[f for f in dir(o) if not callable(getattr(o,f)) and not f.startswith('__')]
Benjamin Toueg 10002
The basic answer is «you can’t do so reliably». See this question.
You can get an approximation with [attr for attr in dir(obj) if attr[:2] + attr[-2:] != ‘____’ and not callable(getattr(obj,attr))] .
However, you shouldn’t rely on this, because:
Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases.
In other words, there is no canonical way to get a list of «all of an object’s attributes» (or «all of an object’s methods»).
If you’re doing some kind of dynamic programming that requires you to iterate over unknwon fields of an object, the only reliable way to do it is to implement your own way of keeping track of those fields. For instance, you could use an attribute naming convention, or a special «fields» object, or, most simply, a dictionary.
BrenBarn 232614
You could use the built-in method vars()
El Bert 2908
Related Query
- How to remove all not float numbers and duplicates from list
- How do I split the values and convert to float in a list if they are all in a single quotation?
- how do I create a dict with all fields and properties of a python object?
- Using the Python mock module, how can I patch a class so that it stubs only the methods I want to stub and leaves other properties and methods alone?
- Python: How do I dynamically alter methods of dict and list objects?
- Python unit tests: How to patch an entire class and methods
- How do I get optparse list all possible arguments and options?
- How do I create a dictionary where every key is a value from a list, and every value is all the values from the list except the key
- How to pass list of function and all its arguments to be executed in another function in python?
- How to pass a class as a parameter and inherit methods
- Python 3, list comprehensions, scope and how to compare against external variables
- How to search through all installed python packages for a class in vscode?
- How to trigger an action after model and related m2m (groups) fields are saved?
- How to use autograph and tf.device with tf.function wrapped class method?
- How can we list all the parameters in the aws parameter store using Boto3? There is no ssm.list_parameters in boto3 documentation?
- How do I build a list of all possible tuples from this table?
- How to double all the values in a list
- How to find all occurrences of a pattern and their indices in Python
- How can I split the Python list and make a new lists in ascending order?
- Given an odd length list of values in Python, how can I swap all values other than the final value in the list?
- How to print a list without it showing brackets and «» in the output ? Python 3.3.2
- How to iterate over a list of lists and print items of each list as a comma-delimited string
- How to divide all the elements in a list together
- How to perform a ‘one-liner’ assignment on all elements of a list of lists in python
- Python: How to register all child classes with the father class upon creation
- Group a list of tuples on two values, and return a list of all the third value
- How to get all permutations of string as list of strings (instead of list of tuples)?
- How can I generate a list of all possible permutations of several letters?
- How do I perform an action on each element of a list and put the results in a new list in Python?
- How do I open all files of a certain type in Python and process them?
- How do I initialize a dictionary with a list of keys and values as empty sets in python3.6?
- How to iterate through an enumerate object and print all the index-item pairs using next() function?
- Python how to iterate over a list 100 elements at a time until I reach all elements?
- Python: How to replace whitespaces by underscore in the name of ALL files, folders and subfolders?
- How to find element in selenium python using id and class in div
- How to change all objects of a class at once?
- Add attribute to class list to return all objects with specific attribute
- How to split a list and into a tuple
- how to count the longest sequence of the same value in a list of lists, and then output the largest sequence in a tuple
- How to find a list of all **args of a function?
More Query from same tag
- Python bdist and distribute packages for install without PyPi
- AttributeError: ‘Pipeline’ object has no attribute ‘_transfer_param_map_to_java’
- tesseract reading values from a table
- Pygame runs without any issues, but nothing is drawn on the screen
- What is the syntax to INSERT datetime variable INTO VALUES
- Use Neo4j in Azure Devops or Azure Machine learning
- importing module in Spyder error
- Magenta installation using «pip install magenta» having errors even on fresh environments
- import from a folder with dots in name — Python
- Python Json parser
- Print list elements by 1 column and 1 row, then 1 column and 2 row and so on till end of the list
- Using third party Python modules in QGIS
- Preserving unknown batch dimension for custom static tensors in Tensorflow
- Why is fpectl — Floating point exception control so dangerous?
- Read a HTML file and show it on a Tkinter window
- Using eval() in python to add numbers
- Pickle module in Java
- Python-automated bulk request for Elasticsearch not working «must be terminated by a newline»
- How do I prevent python deallocating ctypes callbacks at exit-time?
- Python generate all n-permutations of n lists
- rollback to the previous offset when an error is throw while pulling data from Intacct
- How to Share a Jupyter Notebook with a CSV Input
- Regex: How to ignore dots in connected words
- itertools and strided list assignment
- Using colorbar with secondary y axis
- Faking a traceback in Python
- ray intersection misses the target
- Does python’s xml.etree.ElementTree support DTD?
- How can I hide the main window titlebar and place a transparent background in kivy framework?
- What’s the difference between randomly picking a 5-digit number, and picking each digit individually?
- Google app engine QR code decoder
- ConfigParser Duplicate keys in python
- Python function introspection: what members of a class passed as argument are mentioned inside it?
- AWS Lambda function not able to find other packages in same directory
- Splitting a date string within a Nested List to group lists by the month — Python