Python 如何获取“17”操作: class newstr(str): # Inheriting str class def __gt__(self, s): raise RuntimeError("This is an error")

Python 如何获取“17”操作: class newstr(str): # Inheriting str class def __gt__(self, s): raise RuntimeError("This is an error"),python,string,python-2.7,comparison,Python,String,Python 2.7,Comparison,有没有什么好方法可以消除应用于较大较小比较运算符和最小-最大函数字符串的可能性?像化名?问题是,这种行为对我来说毫无用处 所以那“17”我要冒着火焰的危险…:-您可以做的是创建一个新的string类,它与本机类几乎相同,但提供了一组新的相等函数 例如,仅覆盖>操作: class newstr(str): # Inheriting str class def __gt__(self, s): raise RuntimeError("This is an error")

有没有什么好方法可以消除应用于较大较小比较运算符和最小-最大函数字符串的可能性?像化名?问题是,这种行为对我来说毫无用处


所以那“17”我要冒着火焰的危险…:-您可以做的是创建一个新的string类,它与本机类几乎相同,但提供了一组新的相等函数

例如,仅覆盖>操作:

class newstr(str):  # Inheriting str class

    def __gt__(self, s):
        raise RuntimeError("This is an error")
现在


对其他相等条件使用uuu lt_uuuu和uuu eq_uuu。

你的意思是你不想使用比较运算符来比较字符串?我不想让字符串比较变成那样,而是得到一个错误。不。相反,如果你想在数字上比较它们,就不要将值保留为字符串形式。但这不是问题。字符串具有顺序,否则无法对其进行排序。正是该命令通知了操作员。你不能只为字符串禁用它们,不。
class newstr(str):  # Inheriting str class

    def __gt__(self, s):
        raise RuntimeError("This is an error")
In [1]: a = newstr('17')
In [2]: b = newstr('9')

In [3]: a<b
Out[3]: True   #since we haven't override __lt__

In [4]: a>b
Traceback (most recent call last):

  File "<ipython-input-64-f269bf469c37>", line 1, in <module>
    a>b

  File ".../untitled0.py", line 6, in __gt__
    raise RuntimeError("This is an error")

RuntimeError: This is an error