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
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
3 weeks ago - 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.
Discussions

attributes - What is the difference between __set__ and __setattr__ in Python and when should which be used? - Stack Overflow
How do I do that (if I need to) in Python. And if one of __setattr__ or __set__ is used for this, what is the other one used for? More on stackoverflow.com
🌐 stackoverflow.com
setter - Why to use __setattr__ in python? - Stack Overflow
I don't know for why using __setattr__ instead simple referencing like x.a=1. I understand this example: class Rectangle: def __init__(self): self.width = 0 self.height = 0 x= More on stackoverflow.com
🌐 stackoverflow.com
Why used setattr/getattr instead of writing my own methods?
You wouldn't use them in code like this at all. You'd use them when you wanted to dynamically set or get an attribute using a string. But note you shouldn't be writing code like this in the first place. There's no reason to write simple getter or setter methods at all, just access the attributes directly. More on reddit.com
🌐 r/learnpython
16
2
March 13, 2022
Why `self.__setattr__(attr, value)` trigger `__getattribute__`?
In the following example,when the code run to the line self.__setattr__(attr, value),the self.__setattr__ in the line invoke __getattribute__,maybe python interpreter just read part of code: import time class Room: def __init__(self,name): self.name = name def __getattribute__(self,attr): print('in ... More on discuss.python.org
🌐 discuss.python.org
0
0
August 6, 2023
🌐
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. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report ...
🌐
Python Morsels
pythonmorsels.com › __setattr__
Python's __setattr__ method - Python Morsels
June 4, 2024 - Implement a __setattr__ method to control all attribute accesses on a Python object.
🌐
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.
Top answer
1 of 4
18

In python, something like this should be implemented using a property (and then only when they do something useful).

class Foo(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self,y):
        self._x = y

In this example, it would be better to just do (as pointed out by Edward):

class Foo(object):
     def __init__(self):
         self.x = None

since our getter/setter methods don't actually do anything ... However, properties become very useful when the setter/getter actually does something more than just assign/return an attribute's value.

It could also be implemented using __setattr__/__getattr__ (but it shouldn't be implemented this way as it quickly becomes cumbersome if your class has more than 1 property. I would also guess that doing it this way would be slower than using properties):

class Foo(object):
    def __init__(self):
        self._x = None
    def __setattr__(self,attr,obj):
        if(attr == 'x'):
            object.__setattr__(self,'_x',obj)
        else:
            object.__setattr__(self,attr,obj)

    def __getattr__(self,attr):
        if(attr == 'x'):
            return object.__getattr__(self,'_x')
        else:
            return object.__getattr__(self,attr)

In terms of what __setattr__ and __getattr__ actually do... __setattr__/__getattr__ are what are called when you do something like:

myclassinstance = MyClass()
myclassinstance.x = 'foo'  #translates to MyClass.__setattr__(myclassinstance,'x','foo')
bar = myclassinstance.x    #translates to bar=MyClass.__getattr__(myclassinstance,'x')

As for __get__ and __set__: previous posts have discussed that quite nicely.

Note that in python there is no such thing as private variables. In general, in a class member is prefixed with an underscore, you shouldn't mess with it (unless you know what you're doing of course). If it's prefixed with 2 underscores, it will invoke name-mangling which makes it harder to access outside the class. This is used to prevent namespace clashes in inheritance (and those variables are generally also not to be messed with).

2 of 4
9

__set__() is used in descriptors when the descriptor is assigned to. __setattr__() is used when binding to an attribute of an object. Unless you're creating a descriptor, you won't use __set__().

Find elsewhere
🌐
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.
🌐
Autodesk
help.autodesk.com › cloudhelp › ENU › MayaCRE-Tech-Docs › CommandsPython › setAttr.html
setAttr command
Go to: Synopsis. Return value. Related. Flags. Python examples. setAttr( attribute Any [Any...] , [alteredValue=boolean], [caching=boolean], [capacityHint=uint], [channelBox=boolean], [clamp=boolean], [keyable=boolean], [lock=boolean], [size=uint], [type=string])
🌐
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() ...
🌐
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.
🌐
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.org
discuss.python.org › python help
Why `self.__setattr__(attr, value)` trigger `__getattribute__`? - Python Help - Discussions on Python.org
August 6, 2023 - In the following example,when the code run to the line self.__setattr__(attr, value),the self.__setattr__ in the line invoke __getattribute__,maybe python interpreter just read part of code: import time class Room: def __init__(self,name): self.name = name def __getattribute__(self,attr): print('in __getattribute__',attr) return object.__getattribute__(self,attr) def __setattr__(self,attr,value): print('in __setattr__',attr) time.sleep(3) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-setattr-method
Python setattr() method - GeeksforGeeks
July 11, 2025 - Python setattr() method is used to assign the object attribute its value. The setattr() can also be used to initialize a new object attribute.
🌐
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.
🌐
GitConnected
levelup.gitconnected.com › decoding-python-magic-setattr-fe017375bb64
Decoding Python Magic : __setattr__ | by Rahul Beniwal | Level Up Coding
March 14, 2024 - The setattr() function in Python is a built-in function that allows you to set the value of an attribute on an object using a variable for the attribute name.
🌐
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.
🌐
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.
🌐
Python.org
discuss.python.org › python help
__getattr__ Called When Paired with __setattr__ - Python Help - Discussions on Python.org
June 14, 2024 - Hi, I am testing the following test script. As you know, the __getattr__ method gets called when fetching previously undefined attributes. However, if the __setattr__ is added (uncommented), the __getattr__ method is …