Automatically setting getter, setter and deleter in python
decorator, oop, python, python-2.7
Solution
Keep it simple.
If you have functions like that, just use a publicly accessible variable. That is:
class Person(object):
def __init__(self):
self.firstName = None
self.lastName = None
self.age = None
is perfectly fine. A better approach given the usage is to require the data as part of the constructor, thus:
class Person(object):
def __init__(self, firstName, lastName, age):
self.firstName = firstName
self.lastName = lastName
self.age = None
person = Person('Peter', 'Smith', 21)
If you are concerned about which name is which, you can always be specific:
person = Person(firstName='Peter', lastName='Smith', age=21)
In the future, if you need to make it more complex, you can add getters/setters where needed.
Another consideration is that given the constructor, you can create a string conversion function on the `Person` object:
def __str__(self):
return ' '.join([self.firstName, self.lastName])
This then allows you to use it like:
person = Person(firstName='Peter', lastName='Smith', age=21)
print(person)
so you don't need to know how it is implemented internally.
Another consideration is that Chinese/Japanese names place the surname first, people can have multiple last names (esp. in Spain) and can have middle names.
Problem
Ok I've been reading about using the @property decorator in Python rather than specific methods for getting, setting and deleting. Some example code is shown below. ``` class Person(object): def __init__(self): self._firstName = None self._lastName = None self._age = None @property def firstName(self): return self._firstName @firstName.setter def firstName(self, val): self._firstName = val @firstName.deleter def firstName(self): del self._firstName @property def lastName(self): return self._lastName @lastName.setter def lastName(self, val): self._lastName = val @lastName.deleter def lastName(self): del self._lastName @property def age(self): return self._age @age.setter def age(self, val): self._age = val @age.deleter def age(self): del self._age Peter = Person() Peter.firstName = 'Peter' Peter.lastName = 'Smith' Peter.age = 21 print ' '.join([Peter.firstName, Peter.lastName]) ``` As you can see, the majority of the code in the example is devoted to defining the methods. My question is whether there is a way to automatically assign the getter, setter and deleter for each of my variables? In my actual code I have a lot more variables and it seems like a lot of repetitive code setting each method. I realise that for simple cases it may not strictly be necessary however I'd prefer to code the methods in now in case I ever decide to increase the complexity of the class.