2016-03-06 83 views
0

说类的实例是printHelloHello
现在,当我执行下面的代码
print printHello
输出为"HelloPrinted"
现在我想比较printHello用字符串类型,无法实现,因为printHello是类型的实例。 有没有一种方法来捕获print printHello代码的输出并将其用于比较或将printHello的类型转换为字符串,我可以将其用于其他字符串比较? 任何帮助表示赞赏。如何将实例转换为Python中的字符串类型?

+1

这是非常难以遵循的。请添加上下文的代码。 – Chris

+0

您的比较目标是什么?如果你想查看对象是否是某种类型,使用'isinstance(printHello,Hello)'。 – tdelaney

+0

如何在世界上做一个名为“你好”的类最终以便'print printHello'导致'“HelloPrinted”'? 'Hello'有'__str__'或'__repr__'方法吗?你可以用'printHello .__ class __.__ name__'得到这个类的名字,这就是你想要的吗? – tdelaney

回答

0

我想你想:

string_value = printHello.__str__() 

if string_value == "some string": 
    do_whatever() 

__str__()方法由print制作类对象的意义。

+0

我得到了以下错误 >> AttributeError:Hello实例没有属性'__str__' – user2518

+0

请参阅其他答案。 – Will

1

__repr__应该在你的类中定义的用于此目的的特殊方法:

class Hello: 
    def __init__(self, name): 
     self.name= name 

    def __repr__(self): 
     return "printHello" 
2

如果你想特别比较字符串,你可以用两种不同的方式做到这一点。首先是定义为类的__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" 
相关问题