与 += 运算符一起使用字符串和整数的对象

uns*_*le2 6 python

Python中有没有一种方法可以初始化一个变量,以便它可以与+= "a string"或一起工作+= 100使用?\n例如:

\n
a = <what to put here>\na += 100  # a = 100\nb = <same what to put here from above>  \nb += "a string"  # b = "a string"\n
Run Code Online (Sandbox Code Playgroud)\n

如果我使用:

\n
a = ""\na += "a string"  # this will work fine\nb = ""\nb += 0  # -> TypeError\n
Run Code Online (Sandbox Code Playgroud)\n

一旦定义了变量的类型,TypeError如果我尝试+=不同的类型,之后就可以得到 a 。例如:

\n
a = <what to put here>\na += "a string"  # a = "a string"\na += 200  # -> okay to get a TypeError here\n
Run Code Online (Sandbox Code Playgroud)\n

我\xe2\x80\x99m 只对使其适用于整数和字符串感兴趣。

\n

Sil*_*olo 7

这取决于您希望结果是什么样子,但这种方式的一种常见用途是Java 类中的字符串生成器StringBuilder模式。这是一个可以接受语言中的任何对象并使用成分的字符串表示形式将字符串连接在一起的类。我们可以这样写。

class StringBuilder:

    def __init__(self):
        self.body = ""

    def __iadd__(self, other):
        self.body += str(other)
        return self

    def __str__(self):
        return self.body

# Example use
a = StringBuilder()
a += "Hello, "
a += 100
print(a)  # Prints "Hello, 100"
Run Code Online (Sandbox Code Playgroud)

如果您的最终目标是构建一个字符串,那么这就是您想要的。但您也可以使该模式适应其他用例。如果您只想委托+底层类型并使用我们编写的这个虚构类作为一种通用身份,您也可以这样做。

class UniversalIdentity:

    def __add__(self, other):
        return other

    def __radd__(self, other):
        return other

# Example use

# This uses integer addition
a = UniversalIdentity()
a += 100
a += 200
print(a)  # Prints 300

# This uses string concatenation
a = UniversalIdentity()
a += "Hello, "
a += "world!"
print(a)  # Prints "Hello, world!"
Run Code Online (Sandbox Code Playgroud)


Kel*_*ndy 1

a = type('', (), {'__add__': lambda _, x: x})()
a += 100

b = type('', (), {'__add__': lambda _, x: x})()  
b += "a string"

print([a, b])
Run Code Online (Sandbox Code Playgroud)

输出(在线尝试!):

[100, 'a string']
Run Code Online (Sandbox Code Playgroud)

  • 为什么要创建一个名称为空的类,为什么要使用“type()”而不是仅使用“class”语法?OP 从未说过代码必须尽可能小,如果这就是原因的话。 (2认同)
  • @wjandrea 因为这就是问题的代码的样子。以“a = &lt;此处放置的内容&gt;”开头。所以我给了他们一些东西放在那里。 (2认同)