What's the pythonic way to use getters and setters?

后端 未结 8 2327
盖世英雄少女心
盖世英雄少女心 2020-11-21 23:05

I\'m doing it like:

def set_property(property,value):  
def get_property(property):  

or

object.property = value  
value =         


        
8条回答
  •  我寻月下人不归
    2020-11-21 23:50

    Using @property and @attribute.setter helps you to not only use the "pythonic" way but also to check the validity of attributes both while creating the object and when altering it.

    class Person(object):
        def __init__(self, p_name=None):
            self.name = p_name
    
        @property
        def name(self):
            return self._name
    
        @name.setter
        def name(self, new_name):
            if type(new_name) == str: #type checking for name property
                self._name = new_name
            else:
                raise Exception("Invalid value for name")
    

    By this, you actually 'hide' _name attribute from client developers and also perform checks on name property type. Note that by following this approach even during the initiation the setter gets called. So:

    p = Person(12)
    

    Will lead to:

    Exception: Invalid value for name
    

    But:

    >>>p = person('Mike')
    >>>print(p.name)
    Mike
    >>>p.name = 'George'
    >>>print(p.name)
    George
    >>>p.name = 2.3 # Causes an exception
    

提交回复
热议问题