(Dec-07-2017, 04:48 PM)QueenSvetlana Wrote: How would I let client code know to use them as read only, if "getters" are not the Python way?
You can use @property in a way to get more towards read only,if you really need that.
Maybe not with all variables,let say ID should be more protected.
class Car:
def __init__(self, ID, name, tire, engine):
self._ID = ID
self.name = name
self.tire = tire
self.engine = engine
@property
def ID(self):
return self._ID
def __str__(self):
template = "ID: {ID} Name: {name} Tire: {tire} Engine: {engine}"
return template.format(**vars(self))
Use:
>>> car_1 = Car(100, 'Opel', 'Goodyear', 1.9)
>>> car_1.name
'Opel'
>>> car_1.engine = 3.0
>>> car_1.engine
3.0
>>> car_1.ID = 900
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AttributeError: can't set attribute