如何重载str操作,使str(“test”)返回“test”

2024-09-28 23:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重载str操作,以便在执行str(string)操作时保留引号。你知道吗

例如: str(“测试”) 返回测试

我要它返回“测试”

这是我写的,任何帮助都将不胜感激!你知道吗

class Action(MalmoAgent):
    def __init__(self, command = '', value = 0):
        self.__command =  command
        self.__value = value
    def __str__(self):
        return ' " ' + self + ' " '

Tags: selfstringreturninitvaluedefactioncommand
3条回答

只是格式化你的字符串

...  def __str__(self):
...   return '"%s"' % self.whatever

使用repr(),这显然不是实际的字符串。你知道吗

repr('Test')
class MalmoAgent():
    pass

class Action(MalmoAgent):
    def __init__(self, command='', value=0):
        self.__command = command
        self.__value = value

    def __str__(self):
        return '"' + super(Action, self).__str__() + '"'


thing = Action()

print("I have a", thing, "called thing.")

输出

I have a "<__main__.Action object at 0x101ae9a90>" called thing.

相关问题 更多 >