设置属性不起作用-语法错误?

2024-04-25 13:30:26 发布

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

我可能犯了一些基本的错误。。。你知道吗

当我初始化并查看对象的属性时,很好。但是如果我尝试设置它,对象不会自动更新。我试图定义一个我可以设置和获取的属性。为了让它更有趣,这个矩形存储了两倍的宽度而不是宽度,所以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所告诉的对象的实际状态没有改变?我特别困惑,为什么我从来没有看到“setting w=”后面跟着一个数字。你知道吗


Tags: 对象namerectself宽度属性定义def
1条回答
网友
1楼 · 发布于 2024-04-25 13:30:26
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
    """

在python2.x中,property只有从object继承时才能正常工作,这样就可以得到新的样式类。默认情况下,您可以使用旧式类来实现向后兼容性。在python3.x中已经修复了这个问题

相关问题 更多 >