(-2)**0.5和sqrt(-2)是不同的,前者是復(fù)數(shù)后者是會(huì)報(bào)錯(cuò)的。
print((-2)**0.5)#輸出:(8.659560562354934e-17+1.4142135623730951j)import mathmath.sqrt(-2)#報(bào)錯(cuò)ValueError: math domain error
functions = []for i in range(5): def f(x): return x + i functions.append(f)for f in functions: print(f(7))
上面程序的輸出是:1111111111
為什么明明f(x)返回的是x+i,而i是從0到4變化的。按道理執(zhí)行f(x)后的返回值也應(yīng)該是變化的,為何我們執(zhí)行f(x)后是5個(gè)一樣的值。
答:這是因?yàn)閜ython中函數(shù)保存的外面的變量都是存儲(chǔ)的是地址。也就是說(shuō)x+i中的i是地址,循環(huán)執(zhí)行完成后。i這個(gè)地址的值變成了4.所以最后執(zhí)行f(7)就是一直是11==7+4.
不信你可以輸出id(i)
試試。
代碼舉例說(shuō)明
x = [1,2,3]print(x.extend([2,3,4]))'''輸出:[1,2,3,2,3,4]'''print(x.append([2,3,4]))'''輸出:[1,2,3,[2,3,4]]'''
可以看到:
extend()
是把參數(shù)通過(guò)合并的形式融合到原來(lái)的列表里面。(融合)append()
是把參數(shù)當(dāng)做一個(gè)元素加到原來(lái)列表里面。(吞并)看代碼理解這3句話:
class Car: color = 'gray' def describe_car(self): return Car.color def describe_self(self): return self.color test = Car()# 類名取Car.color和self.color初始值是一樣的.因?yàn)榇藭r(shí)他們的地址是完全一樣的.print(test.describe_car()) #輸出:gray print(test.describe_self()) # 輸出:gray print('Carcolor地址:',id(Car.color),'self.color地址:',id(test.color))#你可以看看地址是否相同# 先修改Car.color會(huì)影響self.color。因?yàn)榇藭r(shí)他們的地址是完全一樣的Car.color = 'red'print(test.describe_car()) #輸出:redprint(test.describe_self()) # 輸出:redprint('Carcolor地址:',id(Car.color),'self.color地址:',id(test.color))#你可以看看地址是否相同# 修改self.color不會(huì)影響Car.color,因?yàn)榇藭r(shí)他們地址變得不一樣了。test.color = 'blue'print(test.describe_car()) #輸出:redprint(test.describe_self()) # 輸出:blueprint('Carcolor地址:',id(Car.color),'self.color地址:',id(test.color))#你可以看看地址是否相同# 經(jīng)過(guò)上一步此時(shí)他們兩地址不一樣了。修改Car.color不會(huì)影響self.color。因?yàn)榇藭r(shí)他們的地址是不一樣的Car.color = 'black'print(test.describe_car()) #輸出:blackprint(test.describe_self()) # 輸出:blueprint('Carcolor地址:',id(Car.color),'self.color地址:',id(test.color))#你可以看看地址是否相同
x = (0,1,2)x[0]=-1#這是錯(cuò)誤的會(huì)報(bào)錯(cuò)TypeError: 'tuple' object does not support item assignment
__mul__(self,other)
,調(diào)用這個(gè)魔術(shù)方法是self*other
,它實(shí)際這這樣執(zhí)行的:self.__mul(other)
。
聯(lián)系客服