1

I have a class MyLib with variable x. I do not use this variable outside the class but I do set it from another class outside the package. I would like to know what is the preferred way to set value to the variable x below. Should I set it directly as shown in the code snippet below or Should I create @property and @x.setter functions to set it.

class MyLib:
   def __init__(self, *args, **kwargs)
       self._x = None
   def func_to_process_x():
       # do something

class UseLib:
    self._x = 'ABC'

Note: This question is not about wether to use properties over getter and setters. Rather I would like to know if it is advisable to use properties /getter/setters at all if we can directly use the variables, since nothing is private in Python. Further is it recommended to use properties even when I am not doing anything in the @x.setter function apart from simply assigning the value to the variable. Basically wondering if the overhead of properties is worth in the name of encapsulation (even though it is not encapsulation in pure sense since nothing is private. Please correct me if I am wrong here)

rdp
  • 2,072
  • 4
  • 31
  • 55
  • @ Rvdk. Thanks for the link. But that question talks more about properties vs getter and setter. I am more concerned about accessing the variable directly rather than using properties or getattr/setattr or any other custom getters/setters – rdp Jul 20 '15 at 15:12
  • I am still waiting for an answer on this one. Can the python experts please contribute? – rdp Jul 24 '15 at 15:46

1 Answers1

4

It is rather straightforward: avoid properties as long as you do not need them. One could encounter the following code from people who just switched to Python from C++, C# or Java:

class C:
    _x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

And the very first question: WHY? For sake of looking "OOPish"? Nothing is achieved by the code above, what could not be done via:

class C:
    x = None

That is the beauty of Python properties: you could swap the variable version to properties, without the class API user ever knowing about it. There could be any reasons for that, e.g. logging, validation, business logic etc.:

class C:
    ...
    ...
    @x.setter
    def x(self, value):
        self._x = value
        log('x set to {}'.format(value))

The bottom line: use variables, switch to properties when you need to intercept variables being read and/or written.

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83