🌐
Python Morsels
pythonmorsels.com › __setattr__
Python's __setattr__ method - Python Morsels
June 4, 2024 - That __setattr__ method is the dunder method that Python uses for attribute assignments.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › dunderattr › setattr.html
__setattr__ — Python Reference (The Right Way) 0.1 documentation
>>> # this example uses __setattr__ to dynamically change attribute value to uppercase >>> class Frob: ... def __setattr__(self, name, value): ... self.__dict__[name] = value.upper() ...
Discussions

Using setattr() in python - Stack Overflow
I am looking for someone to explain the basics of how to use, and not use setattr(). My problem arose trying to use one class method/function to return data that is then put in another method/func... More on stackoverflow.com
🌐 stackoverflow.com
python - What's the difference between setattr() and object.__setattr__()? - Stack Overflow
I know that you can't call object.__setattr__ on objects not inherited from object, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters. More on stackoverflow.com
🌐 stackoverflow.com
Python's __get/set/delattr__, ordinary assignment versus __setattr__, __dict__ vs dir() - Software Engineering Stack Exchange
I have a few more related OOP Python questions: What does these attributes do exactly: __get/set/delattr__? Why not use just Myclass.NewAttr = value instead of __setattr__? Why does Python use __di... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 10, 2016
python - How does __setattr__ work with class attributes? - Stack Overflow
I am trying to understand exactly how __setattr__ works with class attributes. This question came about when I attempted to override __setattr__ to prevent attributes from being written to in a sim... More on stackoverflow.com
🌐 stackoverflow.com
🌐
O'Reilly
oreilly.com › library › view › python-in-a › 0596001886 › re13.html
__setattr__ - Python in a Nutshell [Book]
March 3, 2003 - Name__setattr__ Synopsis__setattr__(self, name, value)At every request to bind attribute x.y (typically, an assignment statement x.y = value), Python calls x .__setattr__('y',value... - Selection from Python in a Nutshell [Book]
Author: Alex Martelli
Published: 2003
Pages: 656
🌐
Python Morsels
pythonmorsels.com › python-setattr
Python's setattr function and __setattr__ method - Python Morsels
June 9, 2022 - The setattr function relies on the __setattr__ dunder method under the hood.
🌐
ZetCode
zetcode.com › python › dunder-setattr
Python __setattr__ Method - Complete Guide
April 8, 2025 - The __setattr__ method is called when an attribute assignment is attempted on an object.
🌐
Python
peps.python.org › pep-0726
PEP 726 – Module __setattr__ and __delattr__ | peps.python.org
August 24, 2023 - The __setattr__ function at the module level should accept two arguments, the name of an attribute and the value to be assigned, and return None or raise an AttributeError.
Find elsewhere
🌐
Andreaminini
en.andreaminini.com › python › the-__setattr__-method-in-python
The __setattr__() Method in Python - Andrea Minini
In other words, the `__setattr__()` method defines how the object should respond when someone tries to modify one of its attributes.
🌐
Finxter
blog.finxter.com › home › learn python blog › python __setattr__() magic method
Python __setattr__() Magic Method - Be on the Right Side of Change
January 4, 2022 - Python’s magic method __setattr__() implements the built-in setattr() function that takes an object and an attribute name as arguments and removes the attribute from the object. We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get ...
🌐
W3Schools
w3schools.com › python › ref_func_setattr.asp
Python setattr() Function
The setattr() function sets the value of the specified attribute of the specified object.
Top answer
1 of 2
18

Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.


Original Answer*

setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value)**.

You would only need to call object.__setattr__(...) inside a class definition, and then only if directly subclassing object -- if you were subclassing something else, Spam for example, then you should either use super() to get the next item in the heirarchy, or call Spam.__setattr__(...) -- this way you don't risk missing behavior that super-classes have defined by skipping over them directly to object.


* applies to Python 3.0+ classes and 2.x new-style classes


**There are two instances where setattr(x, ...) and x.__setattr__(...) are not the same:

  • x itself has a __setattr__ in it's private dictionary (so x.__dict__[__setattr__] = ... (this is almost certainly an error)

  • x.__class__ has a __getattribute__ method -- because __getattribute__ intercepts every lookup, even when the method/attribute exists

NB These two caveats apply to every syntactic sugar shortcut:

  • setattr
  • getattr
  • len
  • bool
  • hash
  • etc
2 of 2
-1

Here is an example of the difference between setattr and object.__setattr__

class A:
    def __init__(self):
        self.a = 0

    # overriding default behavior
    def __setattr__(self, name, value):
        self.__dict__[name] = value**2

a = A()
print(a.a) # => 0

a.a = 2
print(a.a) # => 4

setattr(a, 'a', 3)
print(a.a) # => 9

object.__setattr__(a, 'a', 4)
print(a.a) # => 4

To summarize:

  1. setattr() is the function equivalent of the assignment operation. It's like doing my_obj.name = value.

  2. It will call the __setattr__() method of the object's class, which may be overridden in subclasses.

  3. If the attribute is a descriptor, setattr() will trigger its __set__() method.

🌐
Python documentation
docs.python.org › 3 › reference › datamodel.html
3. Data model — Python 3.15.2 documentation
If __setattr__() wants to assign to an instance attribute, it should call the base class method with the same name, for example, object.__setattr__(self, name, value).
Top answer
1 of 1
2

Python Descriptor Methods

What does these attributes do exactly: __get/set/delattr__?

This is a hard one to start with, and fairly advanced - most Python programmers don't need to know this, they just memorize how objects (mostly methods and method decorators) that use this work.

They are special methods that make an object a "descriptor". If that object is looked up through another object, they get invoked. They are how property, classmethod, and staticmethod work. The are also how normal functions can become bound methods.

For example:

>>> class Foo:
...     def __init__(self, bar):
...         self.bar = bar
...     @property
...     def baz(self):
...         return bar * 2
>>> Foo.__init__.__get__
<method-wrapper '__get__' of function object at 0x7f1c1d23b158>

The __get__ is invoked when you do Foo.__init__ (which is invoked by Foo()). It binds the instance to the first argument (we usually call it self) to the method on the dotted lookup.

>>> Foo.baz.__set__
<method-wrapper '__set__' of property object at 0x7f1c1d225e58>

That __set__ method is what is invoked when we try to assign to the baz name on the dotted lookup on the left hand side of the assignment (since we didn't define a setter, baz is read-only) and that method raises the following error:

>>> f = Foo('bar')
>>> f.baz = 'boink'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

I wrote a canonical and very thorough answer on this subject on StackOverflow here.

Assignment versus __setattr__ (versus setattr)

Why not use just Myclass.NewAttr = value instead of __setattr__?

Yes, you should do that. __setattr__ should only be used when implementing special behavior on an object.

There is also a builtin function called setattr - it works if you need to programmatically determine the name you are assigning to, and can't just use a static name in your code.

__dict__ versus dir

Why does Python use __dict__? It keeps the attributes in the end of dir() anyway.

Actually, the attributes (data members) are stored in the dictionary - dir() just looks their names up there.

🌐
Stack Overflow
stackoverflow.com › questions › 39708662 › how-does-setattr-work-with-class-attributes
python - How does __setattr__ work with class attributes? - Stack Overflow
I am trying to understand exactly how __setattr__ works with class attributes. This question came about when I attempted to override __setattr__ to prevent attributes from being written to in a sim...
🌐
Python.org
discuss.python.org › peps
PEP 726: Module __setattr__ and __delattr__ - PEPs - Discussions on Python.org
August 31, 2023 - This PEP proposes supporting user-defined __setattr__ and __delattr__ methods on modules to extend customization of module attribute access beyond PEP 562. Edit: Support defining __setattr__() and __delattr__() in a module · Issue #106016 · python/cpython · GitHub — lists some benefits of new methods for the stdlib.
🌐
Medium
medium.com › @arashtad › immutable-objects-with-setattr-override-b3b3cc833bbb
Immutable Objects with setattr Override | by Arashtad | Medium
July 19, 2025 - To make a class immutable, we can override Python’s special method __setattr__, which is called every time an attribute assignment is attempted.