Python:为什么公共和私有实例属性的行为与属性方法不同

时间:2019-01-15 06:45:09

标签: python

  1. __ init __ 中使用 self.cost = cost ,我们得到以下输出结果

    内部 __ init __

    内部设置器

    内部财产

    100

  2. __ init __ 中使用 self._cost = cost ,我们得到以下输出结果

    内部 __ init __

    内部财产

    100

    在第一点,内部设置器被调用,但在第二点中没有调用。

    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)
    

2 个答案:

答案 0 :(得分:1)

它不是私人的还是公共的,但是您的属性名称是cost,因此self.cost = cost会触发属性设置器,但是self._cost不会,因为没有属性_cost 。它将仅分配新属性_cost

答案 1 :(得分:0)

希望此代码对您来说很清楚。需要考虑的事情很少,装饰器名称应与成员变量CAR ID Time (Sec) Count XXXX 2014-04-03 09:23:00 1 xxxx 2014-04-03 09:33:00 3 . . . . . . 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)