繁体   English   中英

使用属性装饰器的Python运算符重载?

[英]Python operator overloading with property decorator?

我正在看这个Python Doc页面:

http://docs.python.org/2/library/functions.html#property

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

下方显示:

If then c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter.

对我来说,cx = value看起来像是给函数赋值,因为cx是一个函数,除非“ =”运算符被重载。 这是发生什么事了吗?

与del cx相同

谢谢。

property是一个描述符,它改变了Python处理属性访问的方式。 Python文档中有一篇介绍描述符文章

当Python使用__get__方法访问指向对象的属性时,它将返回该方法返回的内容,而不是对象本身。 同样, =将委派给__set__ ,将del委派给__delete__ 特殊方法在docs中进行了描述。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM