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

标签 python class methods attributes

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 在哪里定义?

最佳答案

您是对的,_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 - 类内带下划线定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57222575/

相关文章:

python - Selenium Python - 如何处理随机弹出窗口?

python - 如何在 Python 中打印列表 "nicely"

c++ - C++中变量定义中的'class'关键字

C++类设计: member and local variables

c# - 如何动态找出所有具有自定义属性的方法

python - Django Rest Framework - 如何路由到函数 View

php - 如何使用 foreach 循环在 PHP 和 HTML 数组中回显名字、姓氏和电子邮件地址对象

c# - 这些默认参数的人造模拟之间是否存在显着的机械差异?

java - Java 中覆盖字符串并跳过空格

python - Tensorflow CNN 图像增强管道