【问题标题】:How to overload __str__ operation so str("test") returns "test"如何重载 __str__ 操作以便 str("test") 返回 "test"
【发布时间】:2016-09-12 15:40:18
【问题描述】:

我正在尝试重载 str 操作,以便在我执行 str(string) 时保留引号。

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

我希望它返回“测试”

这是我写的,任何帮助将不胜感激!

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

【问题讨论】:

  • 我很困惑...str("test") 与您的自定义类 Action 有什么关系?
  • str("test") 已经返回 "test",所以即使你的问题的那部分没有意义。

标签: python string operator-overloading


【解决方案1】:

使用repr(),这显然不是一个实际的字符串。

repr('Test')

【讨论】:

  • 如果 OP 期望 'Test'"Test" 保持不同,这将不起作用。
  • 他当然可以更改内容,我只是想教他如何保留引用。
【解决方案2】:

格式化你的字符串

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

【讨论】:

  • 您好,感谢您的回复。你能解释一下你的潜在解决方案吗?为什么要使用 mod 运算符?
  • @ArcherGreenhalgh 这里不是mod 操作符,它被用作字符串格式操作。在此处阅读更多信息:pyformat.info
【解决方案3】:
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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多