【问题标题】:Setting a property doesn't work - dumb syntax error?设置属性不起作用 - 愚蠢的语法错误?
【发布时间】:2012-10-24 17:07:24
【问题描述】:

我可能犯了一些基本的错误......

当我初始化并查看对象的属性时,很好。但是,如果我尝试设置它,该对象不会自行更新。我正在尝试定义一个我可以设置和获取的属性。有趣的是,这个矩形存储了两倍的宽度而不是宽度,所以 getter 和 setter 除了复制之外还有其他事情要做。

class Rect:
    """simple rectangle (size only) which remembers double its w,h
       as demo of properties
    """

    def __init__(self, name, w):
        self.name=name
        self.dwidth=2*w

    def dump(self):
    print "dwidth = %f"  %  (self.dwidth,)


    def _width(self):
        return self.dwidth/2.0

    def _setwidth(self,w):
        print "setting w=", w
        self.dwidth=2*w
        print "now have .dwidth=", self.dwidth

    width =property(fget=_width, fset=_setwidth)

.dwidth 成员变量通常是私有的,但我想在交互式会话中轻松查看它。在 Python 命令行中,我试了一下:

bash 0=> python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rectzzz import *
>>> a = Rect("ack", 10.0)
>>> a.dump()
dwidth = 20.000000
>>> a.width
10.0
>>> a.width=100
>>> a.width
100
>>> a.dump()
dwidth = 20.000000
>>> a.dwidth
20.0
>>> 

为什么 .width 似乎更新了,但是 dump() 和 .dwidth 告诉的对象的实际状态没有改变?我特别困惑为什么我从来没有看到“设置 w=”后跟一个数字。

【问题讨论】:

    标签: python properties


    【解决方案1】:
    class Rect:
        """simple rectangle (size only) which remembers double its w,h
           as demo of properties
        """
    

    应该是:

    class Rect(object):
        """simple rectangle (size only) which remembers double its w,h
           as demo of properties
        """
    

    在 python 2.x 中,property 仅在继承自 object 时才能正常工作,从而获得新的样式类。默认情况下,您会获得用于向后兼容的旧式类。这已在 python 3.x 中修复。

    【讨论】:

    • 就是这样!我因缺乏关注新旧物品的讨论而受苦。不知何故,我知道(对象)是可选的。仅在 3.x 中,但我今天使用的是 2.7。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    相关资源
    最近更新 更多