Python class variables or @property
I am writing a python class to store data, and then another class will instantiate that class to print different variables. Some class variables require a lot of formatting, which can take several lines of code to get it in "final state".
Is it bad practice to just access variables from outside the class with this structure?
class Data():
def __init__(self):
self.data = "data"
Or is it better to use @property method to access variables?
class Data:
@property
def data(self):
return "data"
source to share
Be careful if you do this:
class Data:
@property
def data(self):
return "data"
d = Data()
d.data = "try to modify data"
will give you an error message:
AttributeError: Cannot set attribute
And as I see in your question, you want to be able to transform the data to its final state, so move on to another option
class Data2():
def __init__(self):
self.data = "data"
d2 = Data2()
d2.data = "now I can be modified"
or change the front:
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"
source to share
General practice
It is common practice in Python to expose attributes directly. The property can be added later if additional steps are required during retrieval or configuration.
Most standard library modules follow this practice. Public variables (not prefixed with an underscore) usually do not use the () property unless there is a specific reason (for example, to create a read-only attribute).
Justification
Accessing a normal attribute (no property) is easy to implement, easy to understand, and very fast.
The ability to use the () property later means we don't need to practice defensive programming . We can avoid prematurely injecting getters and setters that bloat the code and make access slower.
source to share
Basically, you can hide a lot of complexity in a property and make it look like an attribute. This improves the readability of the code.
Also, you need to understand the difference between a property and an attribute. Please refer to What is the Difference Between Python Property and Attribute,
source to share