我可以使用布尔值作为列表索引:
isTrue = True
print ('No','Yes')[isTrue] -> 'Yes'
Run Code Online (Sandbox Code Playgroud)
但如果我定义一个类,
class YeaOrNay(object):
def __init__(self, val):
self.val = bool(val)
def __nonzero__(self):
return self.val
def __int__(self):
return int(self.val)
def __str__(self):
return ('Nay','Yea')[self.val]
Run Code Online (Sandbox Code Playgroud)
并尝试以相同的方式使用它:
isTrue = YeaOrNay(True)
print ('No','Yes')[isTrue]
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
TypeError: tuple indices must be integers, not YeaOrNay
Run Code Online (Sandbox Code Playgroud)
我可以解决它,
print ('No','Yes')[int(isTrue)] -> 'Yes'
Run Code Online (Sandbox Code Playgroud)
但是我真的想知道是否有一些魔法类方法可以添加到YeaOrNay中以使其"正常工作".
在python中,bool是一个子类int.这就是为什么你可以使用a bool作为元组的索引.但是,YeaOrNea显然既不是错误,也不是错误.如果你坚持使用这个对象作为元组的索引,子类int (或欺骗它使其工作.bool)
class YeaOrNea(int):
...
Run Code Online (Sandbox Code Playgroud)
否则以正确的方式做到这一点.
print('Yes' if isTrue else 'No')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
538 次 |
| 最近记录: |