I am working on a Python project and since the instance variable names can be directly accessed by specifying class.variablename, I was wondering if it is recommended to implement getter functions for the same. I have not declared the variables as private.
-
1If you can do a thing that's terser, and it enhances readability and reduces runtime complexity, then you should do that thing. Calling a getter costs more than doing a lookup in `self.__dict__`, so it's not just harder to read, it's also *slower*. – Charles Duffy Mar 06 '17 at 22:05
-
2this seems opinion based (off-topic) but I'd think that implementing a getter as a `property` so your attributes can be accessed as such but not tampered with is ideal. – Tadhg McDonald-Jensen Mar 06 '17 at 22:06
-
Start the variable name with one or two underscores if not public. If you want a special getter/setter, create it as private and create a getter/setter. – akg Mar 06 '17 at 22:07
-
1@akg NO. Double-underscores is for *name mangling*, not for making variables "private". There is no concepts of "private vs public" variables in Python. – juanpa.arrivillaga Mar 06 '17 at 22:07
-
1@TadhgMcDonald-Jensen I do think this straddles the line of being based on opinion, however, the `property` decorator is built-in for this very reason, so, it isn't entirely subjective. – juanpa.arrivillaga Mar 06 '17 at 22:09
-
@juanpa.arrivillaga right, but one underscore before the name usually indicates a "private" like intention, like "Don't access it, if you don't want to rewrite your program in the next release. Just in case you really really need it." or so. – akg Mar 07 '17 at 13:36
-
@juanpa.arrivillaga: found a relevant stackoverflow answer: http://stackoverflow.com/questions/7456807/python-name-mangling – akg Mar 07 '17 at 13:38
1 Answers
In languages like Java, you implement getters and setters so that you do not need to change the class's interface if you want to add additional processing (such as value validation, access control, or logging) when getting or setting an attribute. This is particularly important if your classes will be used by applications you didn't write.
In Python, you can add code to attributes with @property
without changing the interface, so you should do that instead. Use regular attribute access to start, and add @property
later if you need to add a behavior.
Even then, keep your getter and setter functions simple. Attribute access is expected to be reasonably quick and you should avoid violating that expectation. If you need to do significant work to obtain a value, a method is appropriate, but give it a descriptive name: calculateFoo()
rather than getFoo()
, for instance.

- 178,883
- 35
- 278
- 309