【python小白】 問關(guān)于property的順序問題
問題描述
代碼如下:
class Test(object): def __init__(self):self.__num = 100 def setNum(self,newNum):print('----setter-----')self.__num = newNumdef getNum(self):print('----getter-----')return self.__numnum = property(getNum,setNum) #get在前,set在后 #num = property(setNum,getNum) #set在前,get在后 t = Test()print(t.getNum())t.setNum(2000)print(t.getNum())print('----'*10)t.num = 5000print(t.num)
運(yùn)行結(jié)果:
在代碼中,property的那一部分,get在前面,set在后面,執(zhí)行結(jié)果正常。然后如果把set放在前面,get放在后面,程序就出錯了。
我想問下,這個為什么跟位置還有關(guān)系呢?不是程序自動識別的么?為什么換了位置就錯誤了?
問題解答
回答1:我試了一下,錯誤信息是:TypeError: getNum() takes 1 positional argument but 2 were given
getter接收一個參數(shù),setter接收兩個參數(shù),互換了傳入的參數(shù)個數(shù)就不匹配了。
這個定義里是有順序的:class property(fget=None, fset=None, fdel=None, doc=None)
相關(guān)文章:
1. javascript - js中遞歸與for循環(huán)同時發(fā)生的時候,代碼的執(zhí)行順序是怎樣的?2. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發(fā)現(xiàn)3. python - linux怎么在每天的凌晨2點(diǎn)執(zhí)行一次這個log.py文件4. php如何獲取訪問者路由器的mac地址5. android - 鍵盤遮擋RecyclerView6. 如何分別在Windows下用Winform項(xiàng)模板+C#,在MacOSX下用Cocos Application項(xiàng)目模板+Objective-C實(shí)現(xiàn)一個制作游戲的空的黑窗口?7. javascript - jQuery each 方法第三個參數(shù)args 如何解釋?8. javascript - 在 vue里面用import引入js文件,結(jié)果為undefined9. java - new + 類名,一定需要申明一個對象嗎?10. javascript - ...mapGetters和...mapState獲取到的state,怎么拿來在methods中操作?
