Skip to main content
 首页 » 编程设计

python之类内带下划线定义的变量

2024年11月24日6lyhabc

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._price在price的两个函数中都用到了,但是变量_price没有在它之前定义用来。

这个类效果不错

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

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

请您参考如下方法:

您是对的,_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 现在被调用了