1

If I have a python class that looks like this:

class MyClass(object):

    def __init__(self, path):
        self.path = path

I know I can change the path attribute in an instance of the object like this:

my_example = MyClass("home/data")
my_example.path = "home/other_data"

However, I have seen some code where people use functions to set attributes like this:

class MyClass(object):

    def __init__(self, path):
        self.path = path

    def setPath(self, path):
        self.path = path

If I want the user of an instance of the class to be able to change an attribute, it is best practice to have a function for this like in the second example, or to just let them change it manually like the first example?

dimachidy
  • 110
  • 1
  • 4
  • 9
  • 1
    If you're working with an attribute, just let the user work with the attribute (first example). See https://docs.quantifiedcode.com/python-anti-patterns/correctness/implementing_java-style_getters_and_setters.html for example. Note that the `@property` stuff might be a little confusing -- one use-case for `@property` is so you can change from using an attribute to function-based getters and setters without destroying your public API. – mgilson Mar 14 '17 at 20:43
  • 2
    If you want to control the getting/setting (for proxying, calculated attributes or validating new values) of the attribute than you can use a [property](https://docs.python.org/3/library/functions.html#property) - otherwise you generally allow attributes to be modified as per your first example, – Jon Clements Mar 14 '17 at 20:47
  • 1
    yes, in Python, unlike Java, no need to create getters / setters, except for properties, to read / update attributes starting with _ (nothing private in python, but kinda understood like private by IDEs and developers). But it's common to have methods setting attributes, post init. – DevLounge Mar 14 '17 at 20:48
  • I see now that the python code I saw that had setters/getters was written by a java developer! Will use pythonic way without them – dimachidy Mar 14 '17 at 21:13

1 Answers1

-1

This depends on the modularity you need in the application. For overall systems design, it's better to make the user access all of the class attributes through class methods. This adds a lot of bloat: get/set methods for each attribute, with further methods for actual manipulation.

In practical terms, you need to decide how much you can trust your user. Python tends to code more directly: let the user make mistakes directly. It's less code for you, and easier for most users.

However, consider the volatility of your design. Do you need to hide the class representation from the user? Do you need to change it once in a while? These are excellent reasons to place the internal representation behind the shield of a simple, unchanging interface: that way, you can change the internals without breaking all of your users' implementations.

Prune
  • 76,765
  • 14
  • 60
  • 81