DEV Community

loading...

Discussion on: Python setter and getter function

Collapse
schwepmo profile image
schwepmo • Edited

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() and setattr() do have nice use cases, for example
you can store attribute names in variables, which allows for some cool stuff (see here).

Collapse
philipstarkey profile image
Phil Starkey

Agreed. Using getattr and setattr 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.

Collapse
fronkan profile image
Fredrik Bengtsson

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.

class MyClass:
    def __init__(self, name):
        self.name = name
me = MyClass("Fredrik")
print(me.name) #Fredrik