[英]How can i override the exactly equal function for a specific string in Python?
I am borderline new to python 我是python的新手
I want to override the == function, in one special case. 在一种特殊情况下,我想覆盖==函数。 namely, I want to "trick" python into thinking that a given string is equal to any other string I compare it to say x = "potato", when comparing any string to x I want it to return True. 即,我想“欺骗” python,让我认为给定的字符串等于任何其他字符串,我将它与x进行比较,将任何字符串与x进行比较时,我希望它返回True。 x == "MANGO" and x == "Tomato" will be True but of course "MANGO" == "Tomato" will still be false x ==“ MANGO”和x ==“ Tomato”将为True,但当然“ MANGO” ==“ Tomato”仍为false
I wish i didn't have to use strings, but it is necessary. 我希望我不必使用字符串,但这是必要的。
If this is not something that can be done, then never mind of course 如果这不是可以做的事,那当然不要紧
you can make a class inheriting from str and overriding eq 您可以使一个类继承自str并覆盖eq
class equalToAllStrings(str):
def __eq__(self, other):
return type(other) is str
x = equalToAllStrings("a")
x == 'b'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.