📜  在Python中使用运算符重载连接两个字符串

📅  最后修改于: 2022-05-13 01:54:44.332000             🧑  作者: Mango

在Python中使用运算符重载连接两个字符串

运算符重载是指使用相同的运算符通过传递不同类型的数据作为参数来执行不同的任务。要了解“+”运算符在Python中如何以两种不同的方式工作,让我们以以下示例为例

Python3
# taking two numbers
a = 2
b = 3
  
# using '+' operator add them
c = a+b
  
# printing the result
print("The sum of these two numbers is ", c)


Python3
# taking two strings from the user
a = 'abc'
b = 'def'
  
# using '+' operator concatenate them
c = a+b
  
# printing the result
print("After Concatenation the string becomes", c)


Python3
# let us define a class with add method
class operatoroverloading:
    
    def add(self, a, b):
        self.c = a+b
        return self.c
  
  
# creating an object of class
obj = operatoroverloading()
  
# using add method by passing integers
# as argument
result = obj.add(23, 9)
print("sum is", result)
  
# using same add method by passing strings
# as argument
result = obj.add("23", "9")
print("Concatenated string is", result)


输出:

The sum of these two numbers is  5

在这个例子中,我们使用“+”运算符来添加数字,现在让我们再举一个例子来了解“+”运算符是如何连接字符串的。

Python3

# taking two strings from the user
a = 'abc'
b = 'def'
  
# using '+' operator concatenate them
c = a+b
  
# printing the result
print("After Concatenation the string becomes", c)

输出:

After Concatenation the string becomes abcdef

为了更好地理解运算符重载,这里有一个例子,其中一个通用方法用于这两个目的。

Python3

# let us define a class with add method
class operatoroverloading:
    
    def add(self, a, b):
        self.c = a+b
        return self.c
  
  
# creating an object of class
obj = operatoroverloading()
  
# using add method by passing integers
# as argument
result = obj.add(23, 9)
print("sum is", result)
  
# using same add method by passing strings
# as argument
result = obj.add("23", "9")
print("Concatenated string is", result)

输出:

sum is 32
Concatenated string is 239