V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
smdbh
V2EX  ›  Python

Python 的一个类能不能和一个 tuple 比较且相等

  •  
  •   smdbh · 322 天前 · 974 次点击
    这是一个创建于 322 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如一个类 Point

    class Point:
    	def __init__():
            self.x
            self.y
    

    和一个 tuple , 例如( 2 ,3 )

    Point 是否可以实现和这个 tuple 直接比较相等,Point(2,3) == (2,3)? 如果可以是实现哪个方法,谢谢

    4 条回复    2023-06-14 17:55:35 +08:00
    with
        1
    with  
       322 天前   ❤️ 1
    Point 类中实现 eq 方法就行
    def __eq__(self, other):
    if isinstance(other, tuple):
    return (self.x, self.y) == other
    elif isinstance(other, Point):
    return (self.x, self.y) == (other.x, other.y)
    else:
    return False
    UN2758
        2
    UN2758  
       322 天前
    ==调用的是__eq__ 方式,自己实现就可以比较了
    MiketsuSmasher
        3
    MiketsuSmasher  
       321 天前 via Android
    在你的类里实现一下 __eq__ 方法,定义一下和 tuple 比较时的行为,这就够了。实例的这个方法会在做相等比较 == 时被调用。
    lanhuermao
        4
    lanhuermao  
       316 天前
    可以的,楼上几位已经说的很清楚了,Python 中的等于比较本质上是对象的 `__eq__` 方法在运算。
    类似的还有:
    __ne__: 不等于
    __gt__: 大于
    __ge__: 大于等于
    __lt__: 小于
    __le__: 小于等于
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3101 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:04 · PVG 23:04 · LAX 08:04 · JFK 11:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.