热线电话:13121318867

登录
2018-12-07 阅读量: 784
怎么理解Inplace和Standard Operators

Python中的Inplace vs Standard Operators


普通操作员执行简单的分配作业。另一方面,Inplace运算符的行为类似于普通运算符,除非它们在可变和不可变目标的情况下以不同的方式运行。

  • _add_方法,做简单的加法,采用两个参数,返回其它变量之和,并将其存储,而无需修改任何参数的。
  • 另一方面,_iadd_方法也接受两个参数,但它通过在其中存储总和来传递第一个参数的就地更改。由于在此过程中需要对象变异,因此不可变目标(如数字,字符串和元组)不应具有_iadd_方法
  • 普通运算符的“add()”方法,实现“ a + b ”并将结果存储在上述变量中​​。
  • Inplace运算符的“iadd()”方法,如果存在则实现“ a + = b ”(即在不可变目标的情况下,它不存在)并更改传递参数的值。但如果没有,则实施“a + b”

在这两种情况下,都需要分配来存储值。

# Python code to demonstrate difference between

# Inplace and Normal operators in Immutable Targets

# importing operator to handle operator operations

import operator

# Initializing values

x = 5

y = 6

a = 5

b = 6

# using add() to add the arguments passed

z = operator.add(a,b)

# using iadd() to add the arguments passed

p = operator.iadd(x,y)

# printing the modified value

print ("Value after adding using normal operator : ",end="")

print (z)

# printing the modified value

print ("Value after adding using Inplace operator : ",end="")

print (p)

# printing value of first argument

# value is unchanged

print ("Value of first argument using normal operator : ",end="")

print (a)

# printing value of first argument

# value is unchanged

print ("Value of first argument using Inplace operator : ",end="")

print (x)

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子