Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 317
APorter1031 Avatar asked Jul 01 '17 02:07

APorter1031


3 Answers

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"
like image 144
A Monad is a Monoid Avatar answered Nov 08 '22 09:11

A Monad is a Monoid


Common Practice

The normal practice in Python is to exposure the attributes directly. A property can be added later if additional actions are required when getting or setting.

Most of the modules in the standard library follow this practice. Public variables (not prefixed with an underscore) typically don't use property() unless there is a specific reason (such as making an attribute read-only).

Rationale

Normal attribute access (without property) is simple to implement, simple to understand, and runs very fast.

The possibility of use property() afterwards means that we don't have to practice defensive programming. We can avoid having to prematurely implement getters and setters which bloats the code and makes accesses slower.

like image 31
Raymond Hettinger Avatar answered Nov 08 '22 09:11

Raymond Hettinger


Basically you could hide lot of complexity in the property and make it look like an attribute. This increases code readability.

Also, you need to understand the difference between property and attribute. Please refer What's the difference between a Python "property" and "attribute"?

like image 1
Manoj Bisht Avatar answered Nov 08 '22 10:11

Manoj Bisht