Python中有没有一种方法可以初始化一个变量,以便它可以与+= "a string"或一起工作+= 100使用?\n例如:
a = <what to put here>\na += 100 # a = 100\nb = <same what to put here from above> \nb += "a string" # b = "a string"\nRun Code Online (Sandbox Code Playgroud)\n如果我使用:
\na = ""\na += "a string" # this will work fine\nb = ""\nb += 0 # -> TypeError\nRun Code Online (Sandbox Code Playgroud)\n一旦定义了变量的类型,TypeError如果我尝试+=不同的类型,之后就可以得到 a 。例如:
a = <what to put here>\na += "a string" # a = "a string"\na += 200 # -> okay to get a TypeError here\nRun Code Online (Sandbox Code Playgroud)\n我\xe2\x80\x99m 只对使其适用于整数和字符串感兴趣。
\n这取决于您希望结果是什么样子,但这种方式的一种常见用途是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)
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)