|
运算符有两种神奇的方法,正常和反射。
# object + other
__or__(self, other)
# Implements bitwise or using the | operator.
# other + object
__ror__(self, other)
# Implements reflected bitwise or using the | operator.
in
运算符只有一种魔术方法。
# item in object
__contains__(self, item)
# __contains__ defines behavior for membership tests using in and not in.
如何实现in
运算符反射魔术方法?
# object in sequence
__rcontains__(self, sequence):
# defines behavior for self in or not in sequence
当你想实现 sql 条件时它会很有用
class Field(object):
def __lt__(self, other):
return '<', self._value, other
Model.objects.filter(Field('a') > 1)
Model.objects.filter(Field('a') in [1, 2, 3, 4])