Skip to main content
 首页 » 编程设计

python之如何定义基本的 Python 结构

2025年05月04日12bluestorm

我正从 Racket 转向 Python。在 Racket 中,我会像这样定义一个 Point 结构:

(struct Point (x y) #:transparent) 

一个点现在是一个包含两个字段的结构,分别命名为 x 和 y。我可以通过调用 equal? 来比较两个结构的(深度)相等性。

Python 中的等价物是什么?在我看来,我必须写十二行:

class Point(): 
    def __init__(self,x,y): 
        self.x = x; 
        self.y = y; 
 
    def __eq__(self, other): 
        return ((type(other) is Point) 
          and self.x == other.x 
          and self.y == other.y) 
 
    def __ne__(self, other): 
        return not(self == other) 

...但肯定有更简单的方法吗?

请您参考如下方法:

是的,好吧,如果您需要整个类来表示您的数据类型,那么您将不得不依赖 __eq__ 和相关的 dunder 方法。但是,在这种特殊情况下,Pythonista 会使用 namedtuple:

from collections import namedtuple 
Point = namedtuple('Point', ['x','y']) 

它将继承 tuple 的所有内容。