zoukankan      html  css  js  c++  java
  • [REPRINT]Properties vs. Getters and Setters

    http://www.python-course.eu/python3_properties.php

    Our new class means breaking the interface. The attribute x is not available anymore. That's why in Java e.g. people are recommended to use only private attributes with getters and setters, so that they can change the implementation without having to change the interface.

    But Python offers a solution to this problem. The solution is called properties!

    The class with a property looks like this:

    class P:
    
        def __init__(self,x):
            self.x = x
    
        @property
        def x(self):
            return self.__x
    
        @x.setter
        def x(self, x):
            if x < 0:
                self.__x = 0
            elif x > 1000:
                self.__x = 1000
            else:
                self.__x = x
    

    A method which is used for getting a value is decorated with "@property", i.e. we put this line directly in front of the header. The method which has to function as the setter is decorated with "@x.setter". If the function had been called "f", we would have to decorate it with "@f.setter".

    Two things are noteworthy: We just put the code line "self.x = x" in the init method and the property method x is used to check the limits of the values. The second interesting thing is that we wrote "two" methods with the same name and a different number of parameters "def x(self)" and "def x(self,x)". We have learned in a previous chapter of our course that this is not possible. It works here due to the decorating:

    >>> from p import P
    >>> p1 = P(1001)
    >>> p1.x
    1000
    >>> p1.x = -12
    >>> p1.x
    0
    >>> 
    

    Alternatively, we could have used a different syntax without decorators to define the property. As you can see, the code is definitely less elegant and we have to make sure that we use the getter function in the init method again:

    class P:
    
        def __init__(self,x):
            self.set_x(x)
    
        def get_x(self):
            return self.__x
    
        def set_x(self, x):
            if x < 0:
                self.__x = 0
            elif x > 1000:
                self.__x = 1000
            else:
                self.__x = x
    
        x = property(get_x, set_x)
    

    There is still another problem in the most recent version. We have now two ways to access or change the value of x: Either by using "p1.x = 42" or by "p1.set_x(42)". This way we are violating one of the fundamentals of Python: "There should be one-- and preferably only one --obvious way to do it."

  • 相关阅读:
    如何度过每天的最初十分钟
    微软正在拿命做一场豪赌
    .htaccess用法与设置超详细讲解+大全
    互联网+情趣用品:羞答答的玫瑰静悄悄地开
    男人雄辩 女人聊天
    苹果手表会一直美下去
    移动应用大行其道:你的企业准备好了吗?
    微商的下一步会怎么走?
    阿里京东腾讯58的O2O格局,创业者的夹缝生存之道
    苹果首席设计师艾维:Apple Watch不是奢侈品
  • 原文地址:https://www.cnblogs.com/yaos/p/14014322.html
Copyright © 2011-2022 走看看