Python 对象@property

发布于 2024-08-02 13:25:32 字数 537 浏览 2 评论 0原文

我正在尝试创建一个点类,它定义一个名为“坐标”的属性。然而,它的行为并不像我预期的那样,我不明白为什么。

class Point:
    def __init__(self, coord=None):
        self.x = coord[0]
        self.y = coord[1]

    @property
    def coordinate(self):
        return (self.x, self.y)

    @coordinate.setter
    def coordinate(self, value):
        self.x = value[0]
        self.y = value[1]

p = Point((0,0))
p.coordinate = (1,2)

>>> p.x
0
>>> p.y
0
>>> p.coordinate
(1, 2)

似乎 px 和 py 由于某种原因没有被设置,即使设置器“应该”设置这些值。有人知道这是为什么吗?

I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why.

class Point:
    def __init__(self, coord=None):
        self.x = coord[0]
        self.y = coord[1]

    @property
    def coordinate(self):
        return (self.x, self.y)

    @coordinate.setter
    def coordinate(self, value):
        self.x = value[0]
        self.y = value[1]

p = Point((0,0))
p.coordinate = (1,2)

>>> p.x
0
>>> p.y
0
>>> p.coordinate
(1, 2)

It seems that p.x and p.y are not getting set for some reason, even though the setter "should" set those values. Anybody know why this is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏闹i 2024-08-09 13:25:32

property 方法(以及扩展后的 @property 装饰器)需要一个新式类,即一个object 的子类。

例如,

class Point:

应该是

class Point(object):

另外,Python 2.6 中添加了 setter 属性(以及其他属性)。

The property method (and by extension, the @property decorator) requires a new-style class i.e. a class that subclasses object.

For instance,

class Point:

should be

class Point(object):

Also, the setter attribute (along with the others) was added in Python 2.6.

溺深海 2024-08-09 13:25:32

如果您从对象派生 Point ,它将起作用:

class Point(object):
    # ...

It will work if you derive Point from object:

class Point(object):
    # ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文