Try the inspect module. getmembers and the various tests should be helpful.

EDIT:

For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

Answer from Matt Luongo on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-get-a-list-of-class-attributes-in-python
How to Get a List of Class Attributes in Python? - GeeksforGeeks
July 12, 2025 - Another way of finding a list of attributes is by using the module inspect. This module provides a method called getmembers() that returns a list of class attributes and methods.
🌐
Mouse Vs Python
blog.pythonlibrary.org › home › how to get a list of class attributes in python
How to Get a List of Class Attributes in Python - Mouse Vs Python
January 31, 2020 - 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.
Discussions

Accessing attributes of a class
How do I access the attributes of a class, such as, __bases__, __name__, __qualname__? When I do this, class C: pass dir(C) then it gives me, ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', ... More on discuss.python.org
🌐 discuss.python.org
0
0
February 22, 2022
Inspect python class attributes - Stack Overflow
The problem is that functions like dir(), inspect.getmembers() and friends return all class attributes including the pre-defined ones like: __class__, __doc__, __dict__, __hash__. This is of course understandable, and one could argue that I could just make a list of named members to ignore, but unfortunately these pre-defined attributes are bound to change with different versions of Python ... More on stackoverflow.com
🌐 stackoverflow.com
Any way to get ALL attributes of an object in python?
movieobject.__dict__ will give you al the attributes and their values movieobject.__dict__.keys() will give you only the names of the attributes. More on reddit.com
🌐 r/learnpython
10
9
June 20, 2024
How to access attributes of a class in a list that was made my iteration?
page_list[0].image would refer to whatever image is referencing in the 1st Page instance in the list. (I'm going with all lowercase here, as your post appears to have mixed cases which you probably didn't intend. Class would usually start with an uppercase, and variables/attributes are usually all lowercase.) PS. Code should perhaps be something like below: class Page: def __init__(self, image, other_stuff) self.image = image self.other_stuff = other def pdfloader(): pages = convert_from_bytes(path) for page in pages: page_list.append(Page(image = page, other_stuff = None)) page_list = [] somepath = Path.cwd() / 'somefolder' pdfloader(somepath) # iterate through list as required for page in page_list: process(page) # page would reference an instance of Page More on reddit.com
🌐 r/learnpython
1
1
July 24, 2023
🌐
Python.org
discuss.python.org › python help
Accessing attributes of a class - Python Help - Discussions on Python.org
February 22, 2022 - When I do this, class C: pass dir(C) then it gives me, ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', ...
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
For instance, if you have a function that formats some data from a file object, you can define a class with methods read() and readline() that get the data from a string buffer instead, and pass it as an argument. Instance method objects have attributes, too: m.__self__ is the instance object with the method m(), and m.__func__ is the function object corresponding to the method.
Top answer
1 of 6
41

Below is the hard way. Here's the easy way. Don't know why it didn't occur to me sooner.

import inspect

def get_user_attributes(cls):
    boring = dir(type('dummy', (object,), {}))
    return [item
            for item in inspect.getmembers(cls)
            if item[0] not in boring]

Here's a start

def get_user_attributes(cls):
    boring = dir(type('dummy', (object,), {}))
    attrs = {}
    bases = reversed(inspect.getmro(cls))   
    for base in bases:
        if hasattr(base, '__dict__'):
            attrs.update(base.__dict__)
        elif hasattr(base, '__slots__'):
            if hasattr(base, base.__slots__[0]): 
                # We're dealing with a non-string sequence or one char string
                for item in base.__slots__:
                    attrs[item] = getattr(base, item)
            else: 
                # We're dealing with a single identifier as a string
                attrs[base.__slots__] = getattr(base, base.__slots__)
    for key in boring:
        del attrs['key']  # we can be sure it will be present so no need to guard this
    return attrs

This should be fairly robust. Essentially, it works by getting the attributes that are on a default subclass of object to ignore. It then gets the mro of the class that's passed to it and traverses it in reverse order so that subclass keys can overwrite superclass keys. It returns a dictionary of key-value pairs. If you want a list of key, value tuples like in inspect.getmembers then just return either attrs.items() or list(attrs.items()) in Python 3.

If you don't actually want to traverse the mro and just want attributes defined directly on the subclass then it's easier:

def get_user_attributes(cls):
    boring = dir(type('dummy', (object,), {}))
    if hasattr(cls, '__dict__'):
        attrs = cls.__dict__.copy()
    elif hasattr(cls, '__slots__'):
        if hasattr(base, base.__slots__[0]): 
            # We're dealing with a non-string sequence or one char string
            for item in base.__slots__:
                attrs[item] = getattr(base, item)
            else: 
                # We're dealing with a single identifier as a string
                attrs[base.__slots__] = getattr(base, base.__slots__)
    for key in boring:
        del attrs['key']  # we can be sure it will be present so no need to guard this
    return attrs
2 of 6
8

Double underscores on both ends of 'special attributes' have been a part of python before 2.0. It would be very unlikely that they would change that any time in the near future.

class Foo(object):
  a = 1
  b = 2

def get_attrs(klass):
  return [k for k in klass.__dict__.keys()
            if not k.startswith('__')
            and not k.endswith('__')]

print get_attrs(Foo)

['a', 'b']

🌐
Reddit
reddit.com › r/learnpython › any way to get all attributes of an object in python?
r/learnpython on Reddit: Any way to get ALL attributes of an object in python?
June 20, 2024 -

I'm using the plex python library to get some info from my plex server.

What I wanted to get was the path of a movie.

I tried to use dir(movie_object), vars(movie_object), and movie_object.__dict__ to try and find all of the movie attributes, and to see where the path was stored.

But there was no attribute that contained the file path information.

In the end I found it under movie_object.location by inspecting the object in the VSCode debugging tools.

Why does VSCode show the location attribute, but dir, vars, or __dict__ do not show it?

Is there a way to reliably get ALL of an objects attributes in python?

Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to access attributes of a class in a list that was made my iteration?
r/learnpython on Reddit: How to access attributes of a class in a list that was made my iteration?
July 24, 2023 -

I've had a lot of issues getting information into and out of a list of classes that I've generated by iteration. In my latest project, I'm using PDF2image to open a pdf and store each page in a list of classes as well as a few other attributes unique to each page. My problem is that I have a really loose grip on how to handle data coming in and out of functions and particularly classes. Like in the following:

'class page():

 def __init__(self, image, other_stuff)

      Self. Image = image

      Self. Other_stuff = other

Page_list = []

def pdfloader():

 Pages = convert_from_bytes(path)

 For page in pages:

      Page_list.append(page(image = page, other_stuff = None))

'

So like, in this example, I've appended 'page_list' with a new instance for each page that was pulled from the pdf and stored as an array. This works great. But now I have no idea how to access each instance to get the array, and then write 'other_stuff' to that instance.

(Also, sorry for the formatting, I'm writing this on mobile and I have to be in bed for work tomorrow. If it makes no sense, I'll take it down and re-post when I get the chance on desktop)

🌐
DigitalOcean
digitalocean.com › community › tutorials › python-getattr
Python getattr() | DigitalOcean
August 3, 2022 - The main reason to use python getattr() is that we can get the value by using the name of the attribute as String. So you can manually input the attribute name in your program from console. Again, if an attribute is not found you can set some default value, which enables us to complete some ...
🌐
CodeSpeedy
codespeedy.com › home › get a list of class attributes in python
Get a List of Class Attributes in Python - CodeSpeedy
January 9, 2022 - Learn how to get a list of the class attributes in Python! * dir() method *vars() method *__dict__ method *getmembers() method
🌐
Toptal
toptal.com › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: An Overly Thorough Guide | Toptal®
January 16, 2026 - Python class attributes can lead to elegant code—as well as bugs. This guide outlines use cases for attributes, properties, variables, objects, and more.
🌐
Quora
quora.com › What-is-the-best-way-to-list-only-the-class-attributes-of-a-class-in-Python
What is the best way to list only the class attributes of a class in Python? - Quora
Use the class dict to get attributes defined directly on that class: attrs = list(MyClass.__dict__.keys()) ... To list only the class attributes of a Python class (i.e., attributes defined on the class object itself, not instance attributes ...
🌐
Turing
turing.com › kb › introduction-to-python-class-attributes
A Guide to Python Class Attributes and Class Methods
Python's classes and objects allow you to design your code in a way that is intuitive and easy to understand. This article will take you through Python class attributes, their purpose and how they’re used as well as class methods and how to create them.
🌐
Built In
builtin.com › software-engineering-perspectives › python-attributes
Python Attributes: Class vs. Instance | Built In
Summary: Python class attributes are shared across all instances, while instance attributes are unique to each object. Attribute lookup starts in the instance’s namespace, then checks the class. Reassigning a class attribute from an instance creates a new instance attribute that shadows the original.
🌐
Medium
medium.com › @satishgoda › python-attribute-access-using-getattr-and-getattribute-6401f7425ce6
Python Attribute Access using __getattr__ and __getattribute__ | by Satish Goda | Medium
December 14, 2019 - After studying the official documentation, I wrote the following simple Python class that overrides the base class implementation and injected some print statements followed by calling base class methods. class Yeah(object): def __init__(self, name): self.name = name # Gets called when an attribute is accessed def __getattribute__(self, item): print '__getattribute__ ', item # Calling the super class to avoid recursion return super(Yeah, self).__getattribute__(item) # Gets called when the item is not found via __getattribute__ def __getattr__(self, item): print '__getattr__ ', item return super(Yeah, self).__setattr__(item, 'orphan')
🌐
AskPython
askpython.com › home › attributes of a class in python
Attributes of a Class in Python - AskPython
February 16, 2023 - Then we use the self keyword to ... self keyword. There are two methods inside the class. The first one “getData()” retrieves the instance attributes......
Top answer
1 of 2
5

That reference isn't describing a special case of the language rules, it's a natural result of everything being an object.

The special case is that MyClass(args...) is wired up to create a new object and call MyClass.__init__ (among other things).

It allows you to change the state of the class after it is defined. This can be as simple as changing "static" data based on some configuration.

class EggsApiClient:
    default_url = "example.com"
    def connect(self):
        # do stuff with default_url

if __name__ = "main":
    EggsApiClient.default_url = parse_args("default_url")
2 of 2
3

This is not something that I think most Python users will ever need to do and almost surely shouldn't but it does have a distinct purpose and it's worth understanding.

Consider the following example:

class Foo:
    def set_a(self, a):
        self.a = a

class Bar:
    def set_b(self, b):
        self.b = b

foo = Foo()

foo.set_a(1)

print(foo.a)

bar = Bar()

# interesting part here!
Foo.set_a(bar, 2)

print(bar.a)

Through this feature, we have effectively called set_a on a Bar instance, despite the fact that Bar doesn't have a set_a method defined. That is, if we try:

bar.set_a()

We get an error: AttributeError: 'Bar' object has no attribute 'set_a'.

You might (quite reasonably) ask, "OK, but why would I do that?" Personally, I think I did something like this many moons ago but there was probably a simpler solution to whatever I was trying to accomplish.

I can imagine this be useful in various frameworks e.g. something like unit testing. But the main reason I think you might end up doing this is when you are using a more functional style. For example, you might have a function like this which has no knowledge of Foo or Bar:

def apply(obj, func, *params):
    func(obj, *params)

Which you can then call like so:

apply(bar, Bar.set_b, 3)

print(bar.b)

A real example of the kind of thing you might actually do:

class Person:
    def __init__(self, name: str, student: bool):
        self.name = name
        self.student = student

    def is_student(self):
        return self.student
    
    def __repr__(self):
        return f"{self.name} - student: {self.student}"
    
people = [Person("bob", False), Person("alice", True), Person("carl", True)]

def display(iter):
    print("---")
    for i in iter:
        print(i)


display(people)

display(filter(Person.is_student, people))

Or maybe something like this:

people = map(Person, ["dave", "edith", "frank"], [True, False, True])

display(people)

Check out the functools module for more interesting functional-style approaches like this.

🌐
GeeksforGeeks
geeksforgeeks.org › python › accessing-attributes-methods-python
Accessing Attributes and Methods in Python - GeeksforGeeks
March 29, 2025 - They can be accessed and invoked using an instance or dynamically using built-in functions. getattr(obj, method): Retrieves a method reference, which can then be called. hasattr(obj, method): Check if the method or attribute exists for a specific ...
🌐
Python.org
discuss.python.org › ideas
Implementing a __class_getattribute__ for using a ClassName.attr notation - Ideas - Discussions on Python.org
July 7, 2023 - Implementation of a __class_getattribute__ Adding a method to a class called __getattribute__ allows the user to modify how items are grabbed from a class, as shown below: class A: def __getattribute__(self, attr): print(attr) a = A() a.print_me ...
🌐
W3Schools
w3schools.com › python › python_class_properties.asp
Python Class Properties
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Properties are variables that belong to a class.