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告诉对象的实际状态不会改变?我特别困惑为什么我从来没有看到“设置w =”后跟一个数字.

最佳答案

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中,如果从对象继承,属性只能正常工作,以便获得新的样式类.默认情况下,您会获得旧式类以实现向后兼容性.这已在python 3.x中修复.

点赞