【问题标题】:Variable with underscore definition inside class类内带下划线定义的变量
【发布时间】:2019-12-04 22:45:40
【问题描述】:
class Ticket:
    def __init__(self, price):
        self.price = price
    @property
    def price(self):
        return self._price
    @price.setter
    def price(self, new_price):
        if new_price < 0:
            raise ValueError('Try again')
        self._price = new_price

在上面的类定义中,self._priceprice的两个函数中都使用了,但是变量_price在使用之前是没有定义的。

这个类像

t = Ticket(4)
print(t.price)
t.price = 34

我想知道这个类是如何工作的?变量_price在哪里定义?

【问题讨论】:

    标签: python class methods attributes


    【解决方案1】:

    你说得对,_price 从未定义过。但是没有错误,因为此代码从不尝试访问它。问题出在这里:

    def __init__(self, price):
        self.price = price
    

    此代码最终将您的 getter 替换为值 4(或您传入的任何值)。我们可以通过向您的 getter 和 setter 添加打印来证明这一点。

    class Ticket:
        def __init__(self, price):
            self.price = price
        @property
        def price(self):
            print('get price')
            return self._price
        @price.setter
        def price(self, new_price):
            print('set price')
            if new_price < 0:
                raise ValueError('Try again')
            self._price = new_price
    

    你会看到什么都没有打印出来。。改成这个。。。

    def __init__(self, price):
        self._price = price
    

    现在你的 getter 和 setter 被调用了

    【讨论】:

    • 这是不是因为Python先跑过defs,设置price()为属性,然后调用__init__(),覆盖了属性?
    • @MichaelKolber 我想是的
    • 我刚刚检查过,这就是原因。在@property 之前、@price.setter 之前和__init__() 之前在self.price = price 之前的主类定义中添加print() 语句将表明这是解释器查看它的顺序。正如预期的那样,注释掉 self.price = price 会引发异常。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2011-10-19
    • 2014-06-09
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多