2

I want to ask if this is the best way of writing a get/ set function for a class static field, that is a property of the class instance, not the class itself?

class MyClass:

    __static_field = "something"

    def __init__(self):
        pass

    @staticmethod
    def get_static_field():
        return MyClass.__static_field

    def get_static_field_with_instance(self):
        return self.__class__.__static_field

    def set_static_field_with_instance(self, new_value):
        self.__class__.__static_field = new_value

Here is some output:

print(MyClass.get_static_field())
>>> something
obj = MyClass()
print(obj.get_static_field_with_instance())
>>> something
obj.set_static_field_with_instance("smething new")
print(obj.get_static_field_with_instance())
>>> something new
stefan.stt
  • 2,357
  • 5
  • 24
  • 47
  • 1
    Why would you use getters and setters with python? You can simply get or set value using ``MyClass.__static_field`` or ``MyClass.__static_field = 'new value'``. Or if you are changing the instance attribute use ``obj.__static_field`` – Gitnik Jun 09 '17 at 10:10
  • @Liliane because I want to encapsulate my data – stefan.stt Jun 09 '17 at 10:11
  • I'm not if encapsulation is needed in python, because python does not have private variables or private methods i.e. [we're all consenting adults here](https://mail.python.org/pipermail/tutor/2003-October/025932.html). – Gitnik Jun 09 '17 at 10:13
  • 1
    @Liliane - yes, but what if i have fields x and y representing coordinates. And what if I have decided from now on they are not x and y, but coords[0] and coords[1]. All those who use my api will have to rewrite their code from .x to .coords[1]. Using getters and setters I will have no such problem – stefan.stt Jun 09 '17 at 10:20
  • I didn't think of that. But do expect that your users will not use the API in the way you have intended. They will probably use it in unexpected ways. For example, if you give a user getter and setter, they may ignore your recommendation to use it, and they will go straight to using class attribute. That way if you down the road change x to coords[0], then you will unintentionally nonetheless break the code of your users. – Gitnik Jun 09 '17 at 15:37

0 Answers0