The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) This is because it doesn't have a __dict__ to hold the attributes.


I generally just do this:

class Object(object):
    pass

obj = Object()
obj.somefield = "somevalue"

But consider giving the Object class a more meaningful name, depending on what data it holds.


Another possibility is to use a sub-class of dict that allows attribute access to get at the keys:

class AttrDict(dict):
    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        self[key] = value

obj = AttrDict()
obj.somefield = "somevalue"

To instantiate the object attributes using a dictionary:

d = {"a": 1, "b": 2, "c": 3}

for k, v in d.items():
    setattr(obj, k, v)
Answer from FogleBird on Stack Overflow
🌐
Medium
medium.com › @nschairer › python-dynamic-class-attributes-24a89df8da7d
Python — Dynamic Class Attributes | by noah | Medium
February 5, 2022 - class Example: def __init__(self): attr1 = 10 #Add an attribute upon initializationexample = Example() example.attr2 = 12 #Add an attribute after initialization · But what if you don’t know what the attributes name is suppose to be? For an object it’s as simple as obj[‘NAME OF ATTR’] = value, but for a class you cannot index with brackets. You will get an object is not subscriptable error.
Discussions

Adding new (undefined) attributes on class instances
David Sampimon is having issues with: I was playing around with classes in Python when I noticed I could add any random attribute to instances with dot notation. Even attributes not ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
April 26, 2022
dynamically add properties to a class (property, __getattribute__, something else?)

Properties must be defined on the class, not the instance. You're assigning the property on self when it needs to be assigned on A.

But dynamically creating attributes like this is weird and messy. The first thing you should do is reconsider whether you really do need to dynamically create attributes. It's an overly complex solution to most problems. Describing your problem to us might be helpful here. If you still decide you need this then you should use __getattr__ (and probably not __getattribute__). Properties are not the right solution.

More on reddit.com
🌐 r/learnpython
17
2
January 4, 2016
Python: How to assign attributes to existing objects?
Hi..., sorry, me again. :wink: Can someone show me the way to assign attributes(with material) to existing objects in Python? # materials are stored in the document's material table index = scriptcontext.doc.Materia… More on discourse.mcneel.com
🌐 discourse.mcneel.com
6
0
March 29, 2017
Setting an attibute of an object as a String
Hello everyone, I hope you’re doing well ! I am actually looking for a certain thing to do. I have a certain object “uut.adder” that might have a hundred different attributes (example: uut.adder.c1,uut.adder.b1, uut.add… More on discuss.python.org
🌐 discuss.python.org
4
0
July 7, 2022
🌐
Vultr Docs
docs.vultr.com › python › built-in › setattr
Python setattr() - Set Attribute Value | Vultr Docs
September 27, 2024 - Design a class with several attribute placeholders. Instantiate the object. Use setattr() to dynamically add or modify attributes.
🌐
Team Treehouse
teamtreehouse.com › community › adding-new-undefined-attributes-on-class-instances
Adding new (undefined) attributes on class instances (Example) | Treehouse Community
April 26, 2022 - if not hasattr(oscar, "wings"): # first, make sure it exists raise AttributeError("object oscar has no wings attribute") oscar.wings = 2 # THEN set it ... Thanks Steven, but what is the use of adding attributes like this? Why would you even want to do that?
🌐
GeeksforGeeks
geeksforgeeks.org › python › add-attributes-in-python-metaclass
How to Add Attributes in Python Metaclass? - GeeksforGeeks
July 23, 2025 - Below is a simple demonstration of how attributes can be defined and added to a Metaclass in Python.
🌐
Reddit
reddit.com › r/learnpython › dynamically add properties to a class (property, __getattribute__, something else?)
r/learnpython on Reddit: dynamically add properties to a class (property, __getattribute__, something else?)
January 4, 2016 -

I'm trying to dynamically add attributes with setters and getters to objects on instantiation. However, I can't figure out how to dynamically add a property to a class. IE:

class A(object):
   def __init__(self):
     self.x = property(lambda self: 'no work :(')

a = A()
print a.x  #prints a property object

class B(object):
  x = property(lambda self: 'works!') #can't be defined on instantiation

b = B()
print b.x  #prints "works!"

What I actually want to do is more like this:

class C(object):
   def __init__(self,attr_objects):
      # generate setters and getters for attributes
      setter  = self._setter_factory
      getter  = self._getter_factory
      for attr in attr_objects:
        setattr(self,attr.name,property(getter(attr),setter(attr)))

My next guess would be to over-ride C.__getattribute__ and C.__setattribute__ so they check if the accessed attribute is one of my dynamically generated ones. If so, call the appropriate function, otherwise handle as usual. Is there a more elegant/pythonic way?

edit: more details on what I'm actually doing:

This is a Data Oriented Programming ORM. I have a DataDomain that has numpy arrays. When you add an "object" to it through the add method, it registers space in those arrays and you get a DataAccessor back that you use to interact with that "instance's" properties. The C class above is my DataAccessor. Like I could have a PolygonDataDomain with arrays of positions and angles of rotation of polygons. When you add a polygon to it, you get an accessor that has a position and angle. When you get or set those values, the getter and setter do it through the PolygonDataDomain arrays. So:

class PolygonDataDomain(DataDomain):
    def __init__(self):
        self.positions = DataArray()
        self.angles = DataArray()
        self._data_oriented_properties = [self.positions, self.angles]

    def add(self, position, angle):
        #register space for this in the DataArrays
        #generate an id through which to keep track of this registered space
        return DataAccessor(self,id)

class DataAccessor(object):
    def __init__(self, domain, id):
        self.__domain = domain
        self.__id = id
        for attr in domain._data_oriented_properties:
            #create an attribute for this attr with appropriate setters and getters

poly_domain = PolygonDataDomain()
poly1 = poly_domain.add( (0,0), 5.)
print dir(poly1) # shows that this "instance" has a position and angle
poly1.position = (2,3) #updates DataArray entry for this "instance"

After creating the PolygonDataDomain subclass, I don't want to have to repeat myself in defining it's properties by having to make a specific PolygonDataAccessor and hard coding it's properties and setters and getters.

Find elsewhere
🌐
MyBlueLinux
mybluelinux.com › how-control-object-attributes-in-python
How Control Object Attributes In Python - MyBlueLinux.com
July 23, 2020 - Unlike Java, which enforces access restrictions on methods and attributes, Python takes the view that we are all adults and should be allowed to use the code as we see fit. Nevertheless, the language provides a few facilities to indicate which methods and attributes are public and which are private, and some ways to dissuade people from accessing and using private things. Let’s take a look at how normal attribute access works. class Foo(object): def __init__(self): self.bar = 1 foo = Foo() foo.bar # Output: 1 foo.bar = 2 foo.bar # Output: 2 foo.__dict__ # Output: {'bar': 2}
🌐
Medium
medium.com › @suryansaravanan › dynamic-attribute-manipulation-in-python-d34bd6c3c2d7
Dynamic Attribute Manipulation in Python | by Suryan Saravanan | Medium
July 8, 2023 - We will explore the various use cases and benefits of using setattr() in Python. Understanding setattr(): The setattr() function allows us to dynamically set attributes on objects during runtime.
🌐
Python.org
discuss.python.org › python help
Setting an attibute of an object as a String - Python Help - Discussions on Python.org
July 7, 2022 - Hello everyone, I hope you’re doing well ! I am actually looking for a certain thing to do. I have a certain object “uut.adder” that might have a hundred different attributes (example: uut.adder.c1,uut.adder.b1, uut.add…
🌐
FastAPI
fastapi.tiangolo.com › tutorial › body
Request Body - FastAPI
The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use None to make it just optional. For example, this model above declares a JSON "object" (or Python dict) like:
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.4 documentation
February 27, 2026 - Changed in version 3.8: Falls back to __index__() if __complex__() and __float__() are not defined. Deprecated since version 3.14: Passing a complex number as the real or imag argument is now deprecated; it should only be passed as a single positional argument. ... This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes.
🌐
Turing
turing.com › kb › introduction-to-python-class-attributes
A Guide to Python Class Attributes and Class Methods
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 of the class. They can be accessed using the class name and through an instance of the class. Class attributes are defined outside of any method, including the init method, and are typically assigned a value directly. ... It's also possible to define class attributes within the class constructor (init) method.
🌐
Python Morsels
pythonmorsels.com › customizing-what-happens-when-you-assign-attribute
Customizing what happens when you assign an attribute - Python Morsels
August 8, 2021 - But in this particular situation (where we have an attribute and we'd like to change how it works) we're kind of stuck. We need some way to hook into the assignment of that attribute. Fortunately, in Python, there is a way to do this: we can use a property.
🌐
GitHub
github.com › python › mypy › issues › 5363
Allow adding attributes to classes after definition · Issue #5363 · python/mypy
July 15, 2018 - For types derived from those, I am able to add class attributes after closing the definition, like so: class State(Enum): OFF = 0 ON = 1 State.labels: Tuple[str,...] = ('Off', 'On') In this contrived example, we are attaching related information to the class, rather than defining it as a completely separate top-level variable like State_labels, which I think is a reasonable design choice (encapsulation, etc). This solution works in Python: labels is indeed a class variable and not an Enum variant.
Author   gwk
🌐
Real Python
realpython.com › python-property
Python's property(): Add Managed Attributes to Your Classes – Real Python
December 15, 2024 - These examples will demonstrate how to validate input data, compute attribute values dynamically, log your code, and more. Then you’ll explore the @property decorator, the most common syntax for working with properties. To get the most out of this tutorial, you should know the basics of object-oriented programming, classes, and decorators in Python. Get Your Code: Click here to download the free sample code that shows you how to use Python’s property() to add managed attributes to your classes.
🌐
Allplan
pythonparts.allplan.com › 2024 › manual › features › attributes › element_attributes
Element attributes - Python API Documentation
The method add_attributes_from_parameters will add all the attribute parameters from the property palette into the list. The method get_attribute_list will cast the BuildingElementAttributeList into a python list of Attribute objects so they can be passed to an AttributeSet object.
🌐
Python
docs.python.org › 3 › library › pickle.html
pickle — Python object serialization
February 23, 2026 - class Foo: attr = 'A class attribute' picklestring = pickle.dumps(Foo) These restrictions are why picklable functions and classes must be defined at the top level of a module. Similarly, when class instances are pickled, their class’s code and data are not pickled along with them. Only the instance data are pickled. This is done on purpose, so you can fix bugs in a class or add methods to the class and still load objects that were created with an earlier version of the class.