是否可以使 python 中的 Instance == string/int/float 或任何数据类型为 True?
Is it possible to make Instance == string/int/float or any datatype to be True in python?
class Element:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return repr(self.value)
example = Element("project", "some project")
example == "some project" # False
有没有办法使上面的语句 True
而不是
example.value == "some project" # True
您可以为您的class实施__eq__()
。
class Element:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return repr(self.value)
def __eq__(self, other):
return self.value == other
example = Element("project", "some project")
这称为 "operator overloading",它允许您为内置运算符(在本例中为 =
运算符)定义自定义行为。
请记住,运算符优先级和结合性都适用。
Python documentation 中有更多相关信息。
您可以尝试在 class 中重载 __eq__
和 __ne__
运算符。
class Element:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other
f = Element("some project")
f == "some project" # True
是的,如评论中所述,您需要覆盖 class
的等号
示例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class foo:
def __init__(self, x=0,name=""):
self.o=x
self.name=name
def __eq__(self, other):
#compare here your fields
return self.name==other
if __name__ == "__main__":
d1 = foo(1,"1")
d2=foo(1,"2")
print (d1=="1")
print ("1"==d1)
class Element:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return repr(self.value)
example = Element("project", "some project")
example == "some project" # False
有没有办法使上面的语句 True
而不是
example.value == "some project" # True
您可以为您的class实施__eq__()
。
class Element:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return repr(self.value)
def __eq__(self, other):
return self.value == other
example = Element("project", "some project")
这称为 "operator overloading",它允许您为内置运算符(在本例中为 =
运算符)定义自定义行为。
请记住,运算符优先级和结合性都适用。
Python documentation 中有更多相关信息。
您可以尝试在 class 中重载 __eq__
和 __ne__
运算符。
class Element:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other
f = Element("some project")
f == "some project" # True
是的,如评论中所述,您需要覆盖 class
的等号示例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class foo:
def __init__(self, x=0,name=""):
self.o=x
self.name=name
def __eq__(self, other):
#compare here your fields
return self.name==other
if __name__ == "__main__":
d1 = foo(1,"1")
d2=foo(1,"2")
print (d1=="1")
print ("1"==d1)