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
Top answer
1 of 4
28

No because the attributes are dynamic (so called instance attributes). Consider the following,

class Foo:
    def __init__( self ):
        self.bar = 1

    def twice( self ):
        self.barbar = 2

f = Foo()
print( list(f.__dict__.keys() ) )
f.twice()
print( list(f.__dict__.keys() ) )

In the first print, only f.bar was set, so that's the only attributes that's shown when printing the attribute keys. But after calling f.twice(), you create a new attribute to f and now printing it show both bar and barbar.

2 of 4
13

Warning - The following isn't foolproof in always providing 100% correct data. If you end up having something like self.y = int(1) in your __init__, you will end up including the int in your collection of attributes, which is not a wanted result for your goals. Furthermore, if you happen to add a dynamic attribute somewhere in your code like Foo.some_attr = 'pork', then you will never see that either. Be aware of what it is that you are inspecting at what point of your code, and understand why you have and don't have those inclusions in your result. There are probably other "breakages" that will not give you the full 100% expectation of what are all the attributes associated with this class, but nonetheless, the following should give you something that you might be looking for.

However, I strongly suggest you take the advice of the other answers here and the duplicate that was flagged that explains why you can't/should not do this.

The following is a form of solution you can try to mess around with:

I will expand on the inspect answer.

However, I do question (and probably would advice against) the validity of doing something like this in production-ready code. For investigative purposes, sure, knock yourself out.

By using the inspect module as indicated already in one of the other answers, you can use the getmembers method which you can then iterate through the attributes and inspect the appropriate data you wish to investigate.

For example, you are questioning the dynamic attributes in the __init__

Therefore, we can take this example to illustrate:

from inspect import getmembers


class Foo:
    def __init__(self, x):
        self.x = x
        self.y = 1
        self.z = 'chicken'


members = getmembers(Foo)

for member in members:
    if '__init__' in member:
        print(member[1].__code__.co_names)

Your output will be a tuple:

('x', 'y', 'z')

Ultimately, as you inspect the class Foo to get its members, there are attributes you can further investigate as you iterate each member. Each member has attributes to further inspect, and so on. For this particular example, we focus on __init__ and inspect the __code__ (per documentation: The __code__ object representing the compiled function body) attribute which has an attribute called co_names which provides a tuple of members as indicated above with the output of running the code.

Discussions

python - Is there any way to get class instance attributes without creating class instance? - Stack Overflow
You cannot do what you want. In python attributes are added to an instance of a class dynamically. Two instances of the same class can have different attributes. More on stackoverflow.com
🌐 stackoverflow.com
June 10, 2016
python - Get class and object attributes of class without methods and builtins - Stack Overflow
Say I have this class: class MyClass(object): my_attrib = 'foo' my_other_attrib = 'bar' def mymethod(): pass Now how can I get ONLY the attributes of the class MyClass, WITHOUT methods ... More on stackoverflow.com
🌐 stackoverflow.com
object oriented - Why access the attributes of a Python class by reference? - Software Engineering Stack Exchange
I generally create an instance ... by this instance object. On my opinion it's better to use a python module which contains functions and global variables than create a class and access its attributes by reference. When or why can it be useful to access the attributes of a class by Attribute references and without an instance ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 9, 2023
using an attribute from a class in python without creating an object - Stack Overflow
The 2025 Stack Overflow and Stack ... of the... ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... Modernizing curation: A proposal for The Workshop and The Archive · 0 Is it possible to read metadata from a python model before creating an instance? 0 Calling class attribute without creating ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - Getting a list of class attributes in Python means identifying all variables defined at the class level, excluding instance attributes and methods.
Top answer
1 of 4
3

If you insist on using an overly general dictionary to initialize your object, just define __init__ to accept, but ignore, the extra keys.

class MyClass(object):
    def __init__(self, attr1, attr2, **kwargs):
        self.attr1 = attr1
        self.attr2 = attr2

d = {'attr1': 'value1', 'attr2': 'value2', 'extra_key': 'value3'}
new_instance = MyClass(**d)

If you can't modify __init__ (as appears to be the case if it inherits from a SQLAlchemy declarative base), add an alternate constructor to accept all the keyword arguments but pick out the ones you need.

class MyClass(Base):
    @classmethod
    def from_dict(cls, **kwargs):
        # Let any KeyErrors propagate back to the caller.
        # They're the one who forgot to make sure **kwargs
        # contained the right keys.
        value1 = kwargs['attr1']
        value2 = kwargs['attr2']
        return cls(value1, value2)

new_instance = MyClass.from_dict(**d)
2 of 4
1

Disclaimer: This answers what OP was asking about (getting attributes of an instance), not what they needed. Which seems to be constructor's parameter list.

You cannot do what you want. In python attributes are added to an instance of a class dynamically. Two instances of the same class can have different attributes. Well... to be precise, there are things called instance attributes, and class attributes.

Instance attributes are the ones associated with the instance of a class. Class attributes are associated with its definition i.e. if you wrote (MyClass.foo)

If you look at the example, the attributes are added during the __init__ on self so they are instance attributes.

What you could do is to create a valid instance and inspect it (look at below example), provide a static list of allowed_keys (e.g. as a class attribute), or in some way require allowed_keys as constructor parameter. All of these are kind of workarounds as what you really need is impossible. They have their pros and cons.

example:

class MyClass(object):
    def __init__(self, value1, value2):
        self.attr1 = value1
        self.attr2 = value2

instance = MyClass(1,2)                        # create a valid object
instance_attributes = instance.__dict__.keys() # inspect it
print(instance_attributes)
🌐
pythontutorials
pythontutorials.net › blog › is-there-a-way-to-list-the-attributes-of-a-class-without-instantiating-an-object
How to List Python Class Attributes Without Creating an Instance — pythontutorials.net
In this example, wheels is a class attribute (we access it via Car.wheels), while color is an instance attribute (only accessible via my_car.color). Our goal is to list attributes like wheels without creating an instance. The built-in dir() function ...
🌐
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 ...
Find elsewhere
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.

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

Top answer
1 of 1
4

The __dict__ attribute holds what you want. The class has it:

>>> class Foo:
...     def __init__(self, x):
...             self.x = x
...
>>> Foo.__dict__
mappingproxy({'__module__': '__main__', '__init__': <function Foo.__init__ at
0x000001CC1821EEA0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__':
<attribute '__weakref__' of 'Foo' objects>, '__doc__': None})

And any instance has it as well:

>>> f = Foo(2)
>>> f.__dict__
{'x': 2}

You should access this attribute through the vars builtin function. Calling vars(foo) will return foo.__dict__. See this related post: Use __dict__ or vars()?.

Documentation for vars:

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.


In addition, I tried and wrote a decorator that might interest you. This is a class decorator, that adds a initKwargs to the class it decorates. Besides, it wraps the __init__ method of that class as well, so as to have it append the kwargs dictionary it receives to the class' initKwargs attribute.

def class_wrapper(cls):
    cls.initKwargs = []
    f = cls.__init__

    def wrapped_init(instance, **kwargs):
        cls.initKwargs.append(kwargs)
        return f(instance, **kwargs)            
    cls.__init__ = wrapped_init

    return cls

@class_wrapper
class Foo:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

Demonstration:

>>> f1 = Foo()
>>> f2 = Foo(a=1, b=2)
>>> f3 = Foo(a=1, b=2, c=3, d=4)
>>> Foo.initKwargs
[{}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2, 'c': 3, 'd': 4}]

I find this approach much cleaner that using vars, because you know what you're accessing since you define it yourself. It gives you more control on the class' behaviour.

🌐
Toptal
toptal.com › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
January 16, 2026 - This is no good—altering our Python class variable via one instance alters it for all the others! At the namespace level all instances of Service are accessing and modifying the same list in Service.__dict__ without making their own data attributes in their instance namespaces. We could get ...
🌐
Built In
builtin.com › software-engineering-perspectives › python-attributes
Python Attributes: Class vs. Instance | Built In
Differences between class attributes and instance attributes in Python. | Video: Geeks Coders ... A class attribute is a Python variable that belongs to a class rather than a particular object. It’s shared between all the objects of this class and is defined outside the constructor function, __init__(self,...), of the class.
🌐
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.org
discuss.python.org › python help
Use instance attributes or class properties inside the class definition? - Python Help - Discussions on Python.org
January 23, 2022 - Let’s say we have this class definition… class Student: def __init__(self): self._permission = False def go_to_party(self): if self._permission: print("Let's party!") else: print("I gotta study some more.") @property def permission(self): return self._permission @permission.setter def permission(self, parental_decision: bool): self._permission = parental_decision @property def is_permitted(self)...
🌐
Turing
turing.com › kb › introduction-to-python-class-attributes
A Guide to Python Class Attributes and Class Methods
Python classes allow for the creation of objects that can have both attributes (data) and methods (functions). Attributes are defined within a class and can be accessed and modified by both the class and its objects. In Python, class attributes are defined directly within the class definition and are shared among all instances ...
🌐
Real Python
realpython.com › python-property
Python's property(): Add Managed Attributes to Your Classes – Real Python
December 15, 2024 - By the end of this tutorial, you’ll understand that: A property in Python is a tool for creating managed attributes in classes. The @property decorator allows you to define getter, setter, and deleter methods for attributes. You use properties when you need controlled access or want to encapsulate logic without changing the API.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-getattr
Python getattr() | DigitalOcean
August 3, 2022 - So, before starting the tutorial, lets see the basic syntax of Python’s getattr() function. getattr(object_name, attribute_name[, default_value]) In this section, we will learn how to access attribute values of an object using getattr() function. Suppose, we are writing a class named Student.
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-display-all-attributes-of-a-class-or-instance-of-a-class-in-Python.php
How to Display All Attributes of a Class or an Instance of a Class in Python
So, if we create a class with an __init__ method that accepts 4 parameters and don't create any additional instance variables, the instance will be composed of these 4 parameters. We can then display all of these parameters with the __dict__ method. If we add in class variables to the class, ...