我是从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)
......但肯定有一种更简单的方法吗?
是的,如果您需要一个完整的类来表示您的数据类型,那么您将不得不依赖于__eq__相关的dunder方法.但是,在这种特殊情况下,Pythonista会使用namedtuple:
from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
Run Code Online (Sandbox Code Playgroud)
哪个将继承所有tuple.
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |