Python:为什么公共实例属性和私有实例属性在属性方法中表现不同

Python:为什么公共实例属性和私有实例属性在属性方法中表现不同,python,Python,使用中的self.cost=cost\uuuu init\uuuu,我们得到以下输出 内部\uuuu初始化\uuuuu 内二传 内部财产 一百 使用中的self.\u cost=cost\uuu init\uuu,我们得到以下输出 内部\uuuu初始化\uuuuu 内部财产 一百 在第一点中,调用了内部setter,但在第2点中没有调用 class Book(object): def __init__(self,cost): print('inside __init__')

使用中的self.cost=cost\uuuu init\uuuu,我们得到以下输出

内部\uuuu初始化\uuuuu

内二传

内部财产

一百

  • 使用中的self.\u cost=cost\uuu init\uuu,我们得到以下输出

    内部\uuuu初始化\uuuuu

    内部财产

    一百

    在第一点中,调用了内部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)
    

  • 它不是private vs.public,但是您的属性名称是
    cost
    ,因此
    self.cost=cost
    会触发属性设置器,但是
    self.\u cost
    不会,因为没有属性
    \u cost
    。它将只分配新属性
    \u cost

    希望此代码能让您明白。需要考虑的事情很少,decorator名称应该与成员变量
    cost
    \u cost
    完全匹配。此外,返回值应为
    \u variablename
    。因此,如果变量名为
    \u cost
    ,则必须返回
    \u cost

    下面是一个小代码示例。 输出:

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


    是,因为当您使用属性
    时,名为
    some\u name
    的属性被激活。注意,
    some\u name
    \u some\u name
    不同。一个下划线没有什么特别之处,它就像任何其他有效的Python标识符一样。在Python中,只有约定的隐私,如果你想继续使用“private”(私有)的一些名称,这种语言不会阻止你。在课本中,为什么要加双下划线(成本)。还有为什么(_cost)出现在uu init方法中。您可以认为它与u没什么不同,但是在python中的某些构造中,您应该在对象之前附加一个u,以利用某些特性。返回的情况就是这样的(双倍)
    inside __init__
    inside setter
    inside property
    10
    ---
    inside __init__
    inside setter
    inside property
    100