如何定义基本的Python结构?

Joh*_*nts 1 python racket

我是从Racket来到Python的.在Racket中,我会定义一个Point这样的结构:

(struct Point (x y) #:transparent)
Run Code Online (Sandbox Code Playgroud)

一个点现在是一个名为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)
Run Code Online (Sandbox Code Playgroud)

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

jua*_*aga 6

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

from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
Run Code Online (Sandbox Code Playgroud)

哪个将继承所有tuple.

  • 还有不止是`Point(1,2)==(1,2)`gotcha:如果你做`Vector = namedtuple('Vector',['angle','magnitude'])`,那么`Point(1 ,2)== Vector(1,2)`是'True`,即使它们的含义非常不同! (2认同)