【问题标题】:Python: Why public and private instance attribute behave differently with property methodsPython:为什么公共和私有实例属性与属性方法的行为不同
【发布时间】:2019-01-15 06:45:09
【问题描述】:
  1. __init__ 中使用 self.cost = cost,我们得到以下输出

    __init__

    里面

    内部设置器

    内部属性

    100

  2. __init__ 中使用 self._cost = cost,我们得到以下输出

    __init__

    里面

    内部属性

    100

    在第一点,内部 setter 被调用,但不是在点 2。

    class Book(object):
        def __init__(self,cost):
        print('inside __init__')
        self.cost = cost
        #self._cost = cost
    
        @property
        def cost(self):
            print('inside property')
            return self._cost
    
        @cost.setter
        def cost(self,value):
            print('inside setter')
            self._cost = value
    
    book = Book(100)
    print(book.cost)
    

【问题讨论】:

  • 是的,因为当您使用属性.some_name 时,会激活一个名为some_name 的属性。请注意,some_name_some_name 不同。单个下划线没有什么特别之处,它就像任何其他有效的 Python 标识符一样。在 Python 中,只有隐私约定,如果您想继续玩“私有”_some_name,该语言不会阻止您。

标签: python


【解决方案1】:

这不是私有与公共的,但是您的属性名称是cost,所以self.cost = cost 会触发属性设置器,但self._cost 不会,因为没有属性_cost。它只会分配新属性_cost

【讨论】:

    【解决方案2】:

    希望这段代码能让你明白。需要考虑的事情很少,装饰器名称应该与成员变量cost_cost 完全匹配。此外,返回应该是_variablename。所以如果你的变量名是_cost,你必须返回__cost

    这是小代码示例。

    class Book_(object):
    def __init__(self,cost):
        print('inside __init__')
        self._cost = cost
    
        @property
        def _cost(self):
            print('inside property')
            return self.__cost
    
        @_cost.setter
        def _cost(self,value):
            print('inside setter')
            self.__cost = value
    
    class Book(object):
        def __init__(self,cost):
            print('inside __init__')
            self.cost = cost
    
        @property
        def cost(self):
            print('inside property')
            return self._cost   ## see the difference with above
    
        @cost.setter ## see the difference with above
        def cost(self,value):
            print('inside setter')
            self._cost = value    ## see the difference with above
    book = Book(10)
    print(book.cost)
    print('---')
    book2 = Book_(100)
    print(book2._cost)
    

    输出:

    inside __init__
    inside setter
    inside property
    10
    ---
    inside __init__
    inside setter
    inside property
    100
    

    【讨论】:

    • 在 Book_ 类中,为什么要加双下划线(cost)。还有为什么在 __init 方法中使用 (_cost)。
    • 您可以认为 _ 没有什么不同,但如果是 python 中的某些构造,您应该在对象之前附加一个 _ 以使用某些功能。返回 __( double _) 就是这种情况
    猜你喜欢
    • 2011-06-01
    • 2023-04-04
    • 1970-01-01
    • 2022-11-22
    • 2015-06-09
    • 2013-01-09
    • 2018-11-12
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多