使用命名tupleples时,似乎有一个默认的"值",允许一个对象将两个命名元组与< >
运算符进行比较。谁能解释此值的来源或为什么此代码返回True
?是否有一种使>
操作员在不使用Person.age
的年龄进行比较的巧妙方法?
>>>from collections import namedtuple
>>>Person = namedtuple('Person', ['age', 'name'])
>>>bob = Person('20', 'bob')
>>>jim = Person('20', '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
?
似乎是在使用字符串比较,只是串联值:
>>> 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