简体   繁体   English

如何在Python中为特定字符串覆盖完全相等的函数?

[英]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.

相关问题 Python字符串匹配完全等于Postgresql相似度函数 - Python String Matching exactly equal to Postgresql Similarity function 如何在 python 中准确获取 lambda 函数的代码? - How can I get exactly the code of a lambda function in python? 在Python 2.7中,如何覆盖单个函数的字符串表示? - In Python 2.7, how do I override the string representation of a single function? 如何检查python中字符串中的特定元素是否相等? - How to check the specific element in string are equal in python? 如何使变量等于一个字符串 - Python - How can I make a variable equal more then one string - Python 如何匹配三个不完全相等的数组中的坐标? - How can I match coordinates from three arrays that are not exactly equal? 如何在python中覆盖默认的字符串格式化程序? - How can I override the default string formatter in python? Python:在单元测试期间如何覆盖复杂的函数? - Python: how can I override a complicated function during unittest? 如何覆盖 Python 2.2.1(WebLogic 版本)中的打印功能 - How can i override print function in Python 2.2.1 (WebLogic version) 如何覆盖 SUBclass 中依次覆盖 SUPERclass 的函数(Python)? - How can I override the function in SUBclass that overrides the SUPERclass in turn (Python)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM