假设Hello
类的实例为printHello
现在,当我执行以下代码时
print printHello
输出为"HelloPrinted"
现在,我想将printHello
与字符串类型进行比较,但无法实现,因为printHello
是实例类型。有没有一种方法可以捕获print printHello
代码的输出并将其用于比较,或者将printHello
类型转换为string,然后我可以将其用于其他字符串比较?任何帮助都是非常感谢的。
发布于 2016-03-06 05:01:09
如果你想专门比较字符串,你可以用两种不同的方法来做。首先是为您的类定义__str__
方法:
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
然后,您可以执行以下操作:
h = Hello()
h == "HelloWorld"
发布于 2016-03-06 04:46:35
在Hello类中定义字符串或repr
更多信息请点击此处- https://docs.python.org/2/reference/datamodel.html#object.
发布于 2016-03-06 04:57:32
为此,应该在您的类中定义一个特殊的方法__repr__:
class Hello:
def __init__(self, name):
self.name= name
def __repr__(self):
return "printHello"
https://stackoverflow.com/questions/35823174
复制