Understanding the pythonic way of dealing with properties

6

I'm trying to figure out how this python properties issue works. But the problem is that in all the net tutorials out there I only find the damn example with only one attribute. I'm looking for an example where you have more to do with day to day. Type with more attributes like name, age, phone, access (boolean), etc. I have doubts like for example, should I create a @property, @setter for each attribute? As would be the example below if we had the data of a person like name, phone, age, email, etc ....

class Person(object):

    def __init__(self):
        self._name = ''

    @property
    def name(self):
        print "Getting: %s" % self._name
        return self._name

    @name.setter
    def name(self, value):
        print "Setting: %s" % value
        self._name = value.title()

    @name.deleter
    def name(self):
        print ">Deleting: %s" % self._name
        del self._name
    
asked by anonymous 01.07.2015 / 01:56

1 answer

4
When you declare the getter , the method can then be used to mark the setter and the deleter (I omitted the deleter of my example to get shorter).

class Pessoa(object):

    def __init__(self):
        self._nome = None
        self._idade = None
        self._telefone = None

    @property
    def nome(self):
        print "Getting: %s" % self._nome
        return self._nome

    @nome.setter
    def nome(self, value):
        print "Setting: %s" % value
        self._nome = value

    @property
    def idade(self):
        print "Getting: %s" % self._idade
        return self._idade

    @idade.setter
    def idade(self, value):
        print "Setting: %s" % value
        self._idade = value

    @property
    def telefone(self):
        print "Getting: %s" % self._telefone
        return self._telefone

    @telefone.setter
    def telefone(self, value):
        print "Setting: %s" % value
        self._telefone = value
    
01.07.2015 / 02:23