Home  >  Q&A  >  body text

[Python Newbie] Asking questions about the order of properties

code show as below:

class Test(object):
    def __init__(self):
        self.__num = 100
        
    def setNum(self,newNum):
        print("----setter-----")
        self.__num = newNum
    
    def getNum(self):
        print("----getter-----")
        return self.__num
    
    num = 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 = 5000
print(t.num)

operation result:

In the code, for the property part, get is in front and set is in the back, and the execution result is normal. Then if you put set in front and get in the back, the program will go wrong.

I would like to ask, why does this have anything to do with location? Isn't it automatically recognized by the program? Why is it wrong to change the position?

仅有的幸福仅有的幸福2662 days ago749

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:37:06

    I tried it and the error message was:
    TypeError: getNum() takes 1 positional argument but 2 were given

    The getter receives one parameter, and the setter receives two parameters. If the number of parameters passed in is exchanged, they will not match.

    There is an order in this definition:
    class property(fget=None, fset=None, fdel=None, doc=None)

    reply
    0
  • Cancelreply