(Oct-20-2021, 07:28 PM)muzikman Wrote: Why use them at all, or when? What questions should I ask myself when designing a class to see if I need them?
Would say in most cases leave it public.
I mean,do not add anything to obscure the name of your attribute if not needed.
Look into
properties
when need to add more control over the attributes.
Let say want control/protect the input US(120V) and Europe(220V).
class Voltage():
def __init__(self, voltage=220, current=15):
self.current = current
self._voltage = voltage
@property
def voltage(self):
return(self._voltage)
@voltage.setter
def voltage(self, voltage):
if voltage in [120, 220]:
self._voltage = voltage
else:
print("The Voltage value has to be either 120 or 240")
Usage:
>>> set_power = Voltage()
>>> set_power.voltage
220
>>> set_power.current
15
>>> set_power.voltage = 150
The Voltage value has to be either 120 or 240
>>> set_power.voltage = 120
>>> set_power.current = 10
>>> set_power.voltage
120
>>> set_power.current
10
To give example how bad it be look at this
image
So the left side code refactor by me,right side try to write as in Java using Python.