为什么要在python中使用@property装饰器? [英] Why should I use the @property decorator in python?

查看:120
本文介绍了为什么要在python中使用@property装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读python教程书,其中简要讨论了属性。据我了解,当请求一个类属性时,python将请求定向到返回该属性的property方法,以便可以在访问该属性之前运行代码。但是为什么有必要这样做,当在下面的示例中,返回的v属性甚至不能使用点表示法访问时?

I have been reading a tutorial book for python and it briefly discussed properties. From what I understand, when a class attribute is requested, python directs the request to the property method that returns the attribute so that code can be run before the attribute is accessed. But why is this necessary, when in the example below, the attribute v being returned cannot even be accessed with dot notation?

@property
def value(self):
    if self.is_face_up:
        v = BJ_Card.RANKS.index(self.rank) + 1
        if v > 10:
            v = 10
    else:
        v = None
    return v 


推荐答案

在函数内部不能用点符号访问属性,因为这将递归调用属性getter并导致堆栈溢出:

The attribute cannot be accessed with dot notation inside the function because that would recursively call the property getter and cause a stack overflow:

class A:
    @property
    def x(self):
        return self.x # StackOverflow

但是, @属性精确地 使其可以使用点符号进行访问。以下是等效的:

However, the whole point of the @property is exactly to make it accessible with dot notation. The following are equivalent:

# Without @property
class A:
    def x(self):
        return 3

a = A()
print(a.x()) # prints 3

# With @property
class A:
    @property
    def x(self):
        return 3

a = A()
print(a.x) # prints 3

这篇关于为什么要在python中使用@property装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆