Following onto yesterday’s post about Python Properties and @property, there is a neat little trick to create a read-only property of a Python class. All you have to do is omit the setter. This Hero class has a read-write property “name”
class Hero(object): def __init__(self, **kwargs): self.name = kwargs['name'] @property def name(self): return '%s %s' % (self.firstname, self.lastname) @name.setter def name(self, name): self.firstname, self.lastname = name.split(' ', 2) if '__main__' == __name__: superman = Hero(name='Kal El') print superman.name print superman.firstname superman.name = 'Clark Kent' print superman.name print superman.firstname # Kal El # Kal # Clark Kent # Clark
You can see it used in the the constructor and in the “superman.name=” statement at the bottom.
We can easily make the name attribute read-only like this:
class Hero(object): def __init__(self, **kwargs): self.firstname, self.lastname = kwargs['name'].split(' ', 2) @property def name(self): return '%s %s' % (self.firstname, self.lastname) if '__main__' == __name__: superman = Hero(name='Kal El') print superman.name print superman.firstname superman.name = 'Clark Kent' # Kal El # Kal # Traceback (most recent call last): # File "/home/art/PycharmProjects/hello/Hero.py", line 14, in <module> # superman.name = 'Clark Kent' # AttributeError: can't set attribute
Note that I had to change the constructor, directly setting self.firstname and self.lastname, since it is no longer valid to write “self.name =”.