如何定义基本的 Python 结构? [英] How to define basic Python structures?
问题描述
我从 Racket 来到 Python.在 Racket 中,我会像这样定义一个 Point
结构:
I'm coming to Python from Racket. In Racket, I would define a Point
structure like this:
(struct Point (x y) #:transparent)
一个点现在是一个结构体,有两个字段,名为 x
和 y
.我可以通过调用 equal?
来比较两个结构的(深度)相等性.
A point is now a structure with two fields named x
and y
. I can compare two structures for (deep) equality by calling equal?
.
Python 中的等价物是什么?在我看来,我必须写十二行:
What is the equivalent in Python? It looks to me like I have to write twelve lines:
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)
...但肯定有更简单的方法吗?
... but surely there's an easier way?
推荐答案
是的,好吧,如果您需要一个完整的类来表示您的数据类型,那么您将不得不依赖 __eq__
和相关的dunder方法.但是,在这种特殊情况下,Pythonista 将使用 namedtuple
:
Yes, well, if you need an entire class to represent your data type, then you will have to rely on the __eq__
and related dunder methods. However, in this particular case, a Pythonista would use a namedtuple
:
from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
这将继承 tuple
的所有内容.
Which will inherit all that from tuple
.
这篇关于如何定义基本的 Python 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!