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

Answer from mgilson on Stack Overflow
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__().

🌐
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

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
August 6, 2023
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 - How to use __setattr__ correctly, avoiding infinite recursion - Stack Overflow
This is also mentioned in the Python docs. 2018-12-07T18:13:19.49Z+00:00 ... @Bakuriu would you please explain what this line is doing exactly? super(MyTest, self).__setattr__(name, value) 2020-04-01T07:03:17.353Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
__getattr__ Called When Paired with __setattr__
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 still called even for existing attributes. More on discuss.python.org
🌐 discuss.python.org
0
June 14, 2024
🌐
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.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) ...
🌐
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
🌐
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 ...
🌐
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.
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
2 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.
🌐
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.
🌐
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 …
🌐
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.
🌐
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.
🌐
Snyk
snyk.io › blog › the-dangers-of-setattr-avoiding-mass-assignment
The dangers of setattr: Avoiding Mass Assignment vulnerabilities in Python | Snyk
February 15, 2023 - A commonly used way to implement mass assignment in Python is the inbuilt setattr() function. This function takes an object, attribute name, and attribute value, and sets the attribute of the object to the provided value.
🌐
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])
🌐
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)}
🌐
Medium
medium.com › @pranaygore › using-getattr-setattr-delattr-hasattr-in-python-6d79c6f9fda3
Using getattr, setattr, delattr, hasattr in Python | by Pranay Gore | Medium
April 21, 2020 - Using getattr, setattr, delattr, hasattr in Python The only use of Python getattr() function is to get the value of an object’s attribute and if no attribute of that object is found, default value …
🌐
Python.org
discuss.python.org › ideas
Extend PEP 562 with __setattr__ for modules? - Ideas - Discussions on Python.org
February 27, 2023 - Since CPython 3.5 it’s possible to customize setting module attributes by setting __class__ attribute. Unfortunately, this coming with a measurable speed regression for attribute access: $ cat b.py x = 1 $ python -m timeit -r11 -s 'import b' 'b.x' 5000000 loops, best of 11: 48.8 nsec per loop $ cat c.py import sys, types x = 1 class _Foo(types.ModuleType): pass sys.modules[__name__].__class__ = _Foo $ python -m timeit -r11 -s 'import c' 'c.x' 2000000 loops, best of 11: 131 nsec per loop For r...