The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Answer from Chris Morgan on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_func_setattr.asp
Python setattr() Function
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 ... class Person: name = "John" age = 36 country = "Norway" setattr(Person, 'age', 40) Try it Yourself »
🌐
Python Morsels
pythonmorsels.com › python-setattr
Python's setattr function and __setattr__ method - Python Morsels
June 9, 2022 - Python's built-in setattr function can dynamically set attributes given an object, a string representing an attribute name, and a value to assign.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › dunderattr › setattr.html
__setattr__ — Python Reference (The Right Way) 0.1 documentation
For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, ... >>> # this example uses __setattr__ to dynamically change attribute value to uppercase >>> class Frob: ... def __setattr__(self, name, value): ...
🌐
Programiz
programiz.com › python-programming › methods › built-in › setattr
Python setattr()
Become a certified Python programmer. Try Programiz PRO! ... The setattr() function sets the value of the attribute of an object. class Student: marks = 88 name = 'Sheeran' person = Student()
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-setattr-method
Python setattr() method - GeeksforGeeks
July 11, 2025 - Before using setattr: name: None descr: None After using setattr: name: GeeksForGeeks descr: CS Portal New attribute created, gfg.value: 5 · Here we are creating attributes of the class 'Dict2Class' dynamically using setattr() function by passing a dictionary with some keys and values to the __init__() method of the class.
Top answer
1 of 5
16

__setattr__() applies only to instances of the class. In your second example, when you define PublicAttribute1, you are defining it on the class; there's no instance, so __setattr__() is not called.

N.B. In Python, things you access using the . notation are called attributes, not variables. (In other languages they might be called "member variables" or similar.)

You're correct that the class attribute will be shadowed if you set an attribute of the same name on an instance. For example:

class C(object):
    attr = 42

 c = C()
 print(c.attr)     # 42
 c.attr = 13
 print(c.attr)     # 13
 print(C.attr)     # 42

Python resolves attribute access by first looking on the instance, and if there's no attribute of that name on the instance, it looks on the instance's class, then that class's parent(s), and so on until it gets to object, the root object of the Python class hierarchy.

So in the example above, we define attr on the class. Thus, when we access c.attr (the instance attribute), we get 42, the value of the attribute on the class, because there's no such attribute on the instance. When we set the attribute of the instance, then print c.attr again, we get the value we just set, because there is now an attribute by that name on the instance. But the value 42 still exists as the attribute of the class, C.attr, as we see by the third print.

The statement to set the instance attribute in your __init__() method is handled by Python like any code to set an attribute on an object. Python does not care whether the code is "inside" or "outside" the class. So, you may wonder, how can you bypass the "protection" of __setattr__() when initializing the object? Simple: you call the __setattr__() method of a class that doesn't have that protection, usually your parent class's method, and pass it your instance.

So instead of writing:

self.PublicAttribute1 = "attribute"

You have to write:

 object.__setattr__(self, "PublicAttribute1", "attribute")

Since attributes are stored in the instance's attribute dictionary, named __dict__, you can also get around your __setattr__ by writing directly to that:

 self.__dict__["PublicAttribute1"] = "attribute"

Either syntax is ugly and verbose, but the relative ease with which you can subvert the protection you're trying to add (after all, if you can do that, so can anyone else) might lead you to the conclusion that Python doesn't have very good support for protected attributes. In fact it doesn't, and this is by design. "We're all consenting adults here." You should not think in terms of public or private attributes with Python. All attributes are public. There is a convention of naming "private" attributes with a single leading underscore; this warns whoever is using your object that they're messing with an implementation detail of some sort, but they can still do it if they need to and are willing to accept the risks.

2 of 5
8

The __setattr__ method defined in a class is only called for attribute assignments on instances of the class. It is not called for class variables, since they're not being assigned on an instance of the class with the method.

Of course, classes are instances too. They're instances of type (or a custom metaclass, usually a subclass of type). So if you want to prevent class variable creation, you need to create a metaclass with a __setattr__ method.

But that's not really what you need to make your class do what you want. To just get a read-only attribute that can only be written once (in the __init__ method), you can probably get by with some simpler logic. One approach is to set another attribute at the end of the __init__ method, which tells __setattr__ to lock down assignments after it is set:

class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self._initialized = True

    def __setattr__(self, name, value):
        if self.__dict__.get('_initialized'):
            raise Exception("Attribute is Read-Only")
        super().__setattr__(name, value)

Another option would be to use property descriptors for the read-only attributes and store the real values in "private" variables that can be assigned to normally. You'd not use __setattr__ in this version:

class Foo:
    def __init__(self, a, b):
        self._a = a
        self._b = b

    @property
    def a(self):
        return self._a

    @property
    def b(self):
        return self._b

foo = Foo(3, 5)
foo.a = 7 # causes "AttributeError: can't set attribute"
Find elsewhere
🌐
Real Python
realpython.com › ref › builtin-functions › setattr
setattr() | Python’s Built-in Functions – Real Python
The built-in setattr() function allows you to set the value of an attribute of an object dynamically at runtime using the attribute’s name as a string. This is particularly useful when you don’t know the attribute names in advance: ... >>> class Person: ...
🌐
Reddit
reddit.com › r/learnpython › why used setattr/getattr instead of writing my own methods?
r/learnpython on Reddit: Why used setattr/getattr instead of writing my own methods?
March 13, 2022 -

Hello fellow pythoners!

I was introduced to the built-in function setattr() and getattr() functions today in regards to classes and started to question why I would want to use these functions instead of writing my own get_attribute and set_attribute methods.

So yeah, why? All my searches just gave me explanations as to how they're used, not why to use it instead of what I was taught back in school.

Is writing my own methods just a translation to how to handle this from someone who came from a language such as java or C# to setting and getting attributes?

Edit: Code example below

class Student:
  def __init__(self, name, grade):
      self.name = name
      self.grade = grade
  def get_name(self):
      return self.name
  def get_grade(self):
      return self.grade
  def set_name(self, name):
      self.name = name
  def set_grade(self, grade):
      self.grade = grade

class Person:
   def __init__(self, name, addr):
      self.name = name
      self.address = addr
   
if __name__ == "__main__":
   george = Student("George", "B")
   jessica = Person("Jessica", "221B Baker Steet")
   print(f"{george.get_name()} has a {george.get_grade()} in English.")
   george.set_grade("A")
   print(f"{george.get_name()} now has a {george.get_grade()} in English")

   print(f"{getattr(jessica, name)} lives on {getattr(jessica, address)}.")
   setattr(jessica, address, "Abbey Road 5")
   print(f"{getattr(jessica, name)} now lives on {getattr(jessica, address)}
🌐
Python
peps.python.org › pep-0726
PEP 726 – Module __setattr__ and __delattr__ | peps.python.org
August 24, 2023 - This PEP proposes supporting user-defined __setattr__ and __delattr__ methods on modules to extend customization of module attribute access beyond PEP 562.
🌐
AskPython
askpython.com › home › python setattr() function
Python setattr() Function - AskPython
February 16, 2023 - Let us look at how we could use this function in our Python programs. It takes the object name, the attribute name and the value as the parameters, and sets object.attribute to be equal to value. Since any object attribute can be of any type, no exception is raised by this function. ... Here is a simple example to demonstrate the use of setattr(). class MyClass(): def __init__(self, name, value): # Set the attribute of the class object setattr(self, name, value) a = MyClass('KEY', 100) print('Printing attribute from Class Object:', a.KEY) print('Printing attribute from getattr():', getattr(a, 'KEY'))
🌐
Codecademy
codecademy.com › docs › python › built-in functions › setattr()
Python | Built-in Functions | setattr() | Codecademy
June 13, 2023 - The setattr() function is a built-in Python function used to set the value of a named attribute of an object.
🌐
Vultr Docs
docs.vultr.com › python › built-in › setattr
Python setattr() - Set Attribute Value | Vultr Docs
September 27, 2024 - This example highlights the dynamic nature of setattr() where the attribute name 'speed' is stored as a string variable and used to set the speed of the car object to 100. Design a class with several attribute placeholders.
🌐
Python
docs.python.org › 3.4 › reference › datamodel.html
3. Data model — Python 3.4.10 documentation
August 2, 2018 - 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).
🌐
Finxter
blog.finxter.com › python-setattr
Python setattr() – Be on the Right Side of Change
It sets the attribute given by the string on the object to the specified value. After calling the function, there’s a new or updated attribute at the given instance, named and valued as provided in the arguments. For example, setattr(object, 'attribute', 42) is equivalent to object.attribute ...
🌐
Python Morsels
pythonmorsels.com › __setattr__
Python's __setattr__ method - Python Morsels
June 4, 2024 - Python evaluates attribute assignments by calling an object's __setattr__ method. That __setattr__ method is the dunder method that Python uses for attribute assignments. ... The actual attribute assignment is handled by the default __setattr__ ...
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
3 weeks ago - For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module. ... This is the counterpart of getattr(). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
🌐
Javatpoint
javatpoint.com › python-setattr-function
Python setattr() function with Examples - Javatpoint
We are excited to announce that we are moving from JavaTpoint.com to TpointTech.com on 10th Feb 2025. Stay tuned for an enhanced experience with the same great content and even more features. Thank you for your continued support · Python setattr() function is used to set a value to the object's ...
🌐
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 ...