相关疑难解决方法(0)

@property装饰器如何工作?

我想了解内置函数的property工作原理.令我困惑的是,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.")
Run Code Online (Sandbox Code Playgroud)

property的论点是getx,setx,delx和文档字符串.

在下面的代码中property用作装饰器.它的对象是x函数,但在上面的代码中,参数中没有对象函数的位置.

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

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
Run Code Online (Sandbox Code Playgroud)

而且,如何在 …

python properties decorator python-internals python-decorators

889
推荐指数
12
解决办法
46万
查看次数

什么时候在Python中初始化类变量?

考虑以下Python 3代码:

class A:
    b = LongRunningFunctionWithSideEffects()
Run Code Online (Sandbox Code Playgroud)

什么时候会LongRunningFunctionWithSideEffects()叫?目前该模块已导入?还是目前以某种方式首次使用该类?

python static initialization class

4
推荐指数
2
解决办法
1201
查看次数