如果属性samp

2024-09-29 23:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在《核心Python编程》一书中,有一个关于如何使用属性的示例。代码如下:

class Hidex(object):
    def __init__(self, x):
        self.__x = x
    @property
    def x():
        def fget(self):
            return ~self.__x
        def fset(self, x):
            assert isinstance(val, int), 'val must be int'
            self.__x = ~x
        return locals()

书中说,这个类将使用以下代码:

inst = Hidex(20)
print inst.x
inst.x = 30
print inst.x

但我觉得这门课不行。因为当访问inst.x时,解释器将实际运行Hidex.__dict__['x'].__get__(x, Hidex),并且因为x=property(x),property的第一个参数'fget'是x,而不是x()中定义的函数'fget'

另外,当我运行此代码时,得到的结果是:

{'fget': <function fset at 0x.....>, 'self': <__main__.xxxx>, 'fget': <function fget at 0x....>}
traceback:
...... # this result is just telling t.x = 30 cannot run, just skip the details
AttributeError: cannot set attribute

我错过什么了吗?为什么这本书能起作用


Tags: 代码selfreturndeffunctionpropertyvalat
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:12

这很有意义:

class Hidex(object):

    def __init__(self, x):
        self.__x = x

    @property
    def x(self):
            return ~self.__x

    @x.setter
    def x(self, x):
        assert isinstance(x, int), 'val must be int'
        self.__x = ~x

看起来你的问题代码中的@property不是内置的,而是另一个版本

这很可能是本文的意图:

def nested_property(func):
    """Make defining properties simpler.
    """
    names = func()
    names['doc'] = func.__doc__
    return property(**names)


class Hidex(object):
    def __init__(self, x):
        self.__x = x
    @nested_property
    def x():
        def fget(self):
            return ~self.__x
        def fset(self, x):
            assert isinstance(x, int), 'val must be int'
            self.__x = ~x
        return locals()

相关问题 更多 >

    热门问题