Search code examples
pythonpropertiesgetter-setter

Python class variables or @property


I am writing a python class to store data and then another class will create an instance of that class to print different variables. Some class variables require a lot of formatting which may take multiple lines of code to get it in its "final state".

Is it bad practice to just access the variables from outside the class with this structure?

class Data():
    def __init__(self):
        self.data = "data"

Or is it better practice to use an @property method to access variables?

class Data:
    @property
    def data(self):
        return "data"

Solution

  • Be careful, if you do:

    class Data:
        @property
        def data(self):
            return "data"
    
    d = Data()
    d.data = "try to modify data"
    

    will give you error:

    AttributeError: can't set attribute

    And as I see in your question, you want to be able to transform the data until its final state, so, go for the other option

    class Data2():
        def __init__(self):
            self.data = "data"
    
    d2 = Data2()
    d2.data = "now I can be modified"
    

    or modify the previus:

    class Data:
      def __init__(self):
        self._data = "data"
    
      @property
      def data(self):
          return self._data
    
      @data.setter
      def data(self, value):
        self._data = value
    
    d = Data()
    d.data = "now I can be modified"