class Hello:
def __init__(self, data="HelloWorld"):
self._data = data
def __str__(self):
return self._data
然后可以将字符串与以下项进行比较:
h = Hello()
str(h) == "HelloWorld"
或者您可以特别使用__eq__特殊函数:
class Hello:
def __init__(self, data="HelloWorld"):
self._data = data
def __str__(self):
return self._data
def __eq__(self, other):
if isinstance(other, str):
return self._data == other
else:
# do some other kind of comparison
如果你想特别地比较字符串,你可以用两种不同的方法。首先是定义类的
__str__
方法:然后可以将字符串与以下项进行比较:
或者您可以特别使用
__eq__
特殊函数:然后您可以执行以下操作:
在Hello类中定义str或repr
更多信息-https://docs.python.org/2/reference/datamodel.html#object.str
为此,应该在类中定义一个特殊的方法repr:
相关问题 更多 >
编程相关推荐