Namedtuple大于或小于运算符,给出意外结果

2024-04-25 22:47:10 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用namedtuples时,对象似乎有一个默认的“值”,允许使用< >运算符比较两个命名元组。有人能解释这个值从哪里来吗?为什么这段代码返回True?有没有一种聪明的方法可以让>运算符在不使用Person.age的情况下比较年龄?在

>>>from collections import namedtuple
>>>Person = namedtuple('Person', ['age', 'name'])
>>>bob = Person('20', 'bob')
>>>jim = Person('20', 'jim')
>>>bob < jim
True

Tags: 对象方法代码trueage情况运算符namedtuple
2条回答

它似乎在使用字符串比较,只是将值串联起来:

>>> Person = namedtuple('Person', ['age', 'name'])
>>> bob = Person('20', 'bob')
>>> jim = Person('20', 'jim')
>>> bob < jim
True
>>> bob = Person('20', 'jin')
>>> bob < jim
False
>>> bob = Person('20', 'jim')
>>> bob < jim
False
>>> bob = Person('21', 'jim')
>>> bob < jim
False
>>> bob = Person('19', 'jim')
>>> bob < jim
True

你可以这样做:

from collections import namedtuple

class Person(namedtuple('Person', ['age', 'name'])):
    def __gt__(self, other):
        return self.age > other.age

    def __lt__(self, other):
        return self.age < other.age

    def __eq__(self, other):
        return self.age == other.age

然而,一个Person在年龄上小于或大于真的有意义吗?为什么不显式地检查Person.age?在

相关问题 更多 >