The Python setattr()
function corresponds to the function getattr()
. It set the attribute values of an object.
Python is an object orientated language, so you can have multiple objects in your applications run-time.
Objects (from classes) can have unique values. These values should be set using a getter and setter function. Python has the functions setattr()
and getattr()
for that.
The setattr() syntax is:
setattr (object, name, value)
with parameters:
- Object: the object.
- Name: string, object properties.
- Value: property value.
examples
The following examples illustrate setattr()
function using the method:
>>> class A:
... foo = 1
...
>>> obj1 = A()
>>> getattr(obj1, 'foo')
1
>>> setattr(obj1, 'foo', 6)
>>> getattr(obj1, 'foo')
6
>>>
Of course you can use properties without getter and setter, but that's a bad practice.
>>> obj1.foo
6
>>> obj1.foo = 7
>>>
If the property does not exist will create a new object property, and it will do property assignment:
>>> obj1.name = "Alice"
>>> getattr(obj1, 'name')
'Alice'
>>>
This modifies the existing object only, not the class the object is derived from.
>>> dir(A)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foo']
>>>
But you should define all properties in the class, this is a best practice.
Related links:
Top comments (3)
I don't really agree with the statement, that it's bad practice to not use getters and setters in python. I actually think it's one of the beauties of python, that you don't have to clutter you classes with unnecessary code.
foo.bar
is totally valid to retrieve an attribute imo.That being said
getattr()
andsetattr()
do have nice use cases, for exampleyou can store attribute names in variables, which allows for some cool stuff (see here).
Agreed. Using
getattr
andsetattr
is really only pythonic when the attribute name is variable.The language in this article is also completely wrong. They seem to call attributes 'properties' which are actually a completely different thing in python (but also uses the phrases: getters and setters)
I feel like the author is very confused about all of this.
I also agree with these comments. Furthermore, this will completely break all help a good ide or text editor will give you, like suggestions and auto-completion. I have never seen this style of coding before. You usually define all fields of a class inside the dunder init method of the class.