Sin*_*ion 9 python operator-overloading
在python中我们可以说:
if foo < bar < baz:
do something.
Run Code Online (Sandbox Code Playgroud)
同样,我们可以重载比较运算符,如:
class Bar:
def __lt__(self, other):
do something else
Run Code Online (Sandbox Code Playgroud)
但实际上调用了那些区间比较的操作数类型的哪些方法呢?是以上相当于
if foo.__lt__(bar) and bar.__lt__(baz):
do something.
Run Code Online (Sandbox Code Playgroud)
编辑:re S.Lott,这里有一些输出有助于说明实际发生的事情.
>>> class Bar:
def __init__(self, name):
self.name = name
print('__init__', self.name)
def __lt__(self, other):
print('__lt__', self.name, other.name)
return self.name < other.name
>>> Bar('a') < Bar('b') < Bar('c')
('__init__', 'a')
('__init__', 'b')
('__lt__', 'a', 'b')
('__init__', 'c')
('__lt__', 'b', 'c')
True
>>> Bar('b') < Bar('a') < Bar('c')
('__init__', 'b')
('__init__', 'a')
('__lt__', 'b', 'a')
False
>>>
Run Code Online (Sandbox Code Playgroud)
Mik*_*iak 12
if foo < bar < baz:
Run Code Online (Sandbox Code Playgroud)
相当于
if foo < bar and bar < baz:
Run Code Online (Sandbox Code Playgroud)
有一个重要的区别:如果bar是变异的,它将被缓存.即:
if foo < bar() < baz:
Run Code Online (Sandbox Code Playgroud)
相当于
tmp = bar()
if foo < tmp and tmp < baz:
Run Code Online (Sandbox Code Playgroud)
但要回答你的问题,最终会:
if foo.__lt__(bar) and bar.__lt__(baz):
Run Code Online (Sandbox Code Playgroud)
你是对的:
class Bar:
def __init__(self, name):
self.name = name
def __lt__(self, other):
print('__lt__', self.name, other.name)
return True
a,b,c = Bar('a'), Bar('b'), Bar('c')
a < b < c
Run Code Online (Sandbox Code Playgroud)
输出:
('__lt__', 'a', 'b')
('__lt__', 'b', 'c')
True
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1305 次 |
最近记录: |