-
Tip of the day: Virtual object properties
Here’s a trick I learned today from Chris that’s worth sharing: creating “virtual” attributes for objects (in need for a better wording).
Here’s a use-case: we have a person with a Name and a Surname — how could we access its full name in one string like
person.full_name? You could do that with Python’s@propertydecorator:class Person(object): def __init__(self, name, surname): self.name = name self.surname = surname @property def full_name(self): return "%s %s" % (self.name, self.surname) p=Person('John', 'Doe') print (p.name, p.surname) ('John', 'Doe') print p.full_name John DoeWithout the decorator we would need to access the string as
person.full_name(), instead of the simpler and more intuitiveperson.full_name. Pretty neat.
