简体   繁体   中英

python nested function, missing 1 required positional argument

I am learning python from the beginning. Just start to learn nested functions. These days I got some good code as below:

def w(m , g): 
    return m * g
def weight(g):
    def cal_mg(m):
        return m * g
    return cal_mg
w = weight(10)
G = w(100)
G2 = w(50)
print(G)

It gives me "1000", which I have no problem with. When I start to learn this, I wrote:

   def w(m, g): 
       return m*g
   def weight(g):
       def cal_mg(m):
           return m*g
       return cal_mg
   w_1=weight(10)
   G=w(100)
   print(G)

I got "TypeError: w() missing 1 required positional argument: 'g'". I feel like I was typing the exactly same code. Why it keeps asking about another argument 'g'.

Anyone can help me with this? thanks

That's because you referenced function w as well, which requires, as you stated, g and m .

   def w(m, g): 
       return m*g
   def weight(g):
       def cal_mg(m):
           return m*g
       return cal_mg
   w_1=weight(10)
   G=w(100, 100)
   print(G)

would be a possible solution; this way you satisfy all requirements. Function weight only requires ```g``.

This is because in the first example you are filling both the positional arguments. That is once in line 7 when u assign the weight function to w and the second time in line 8 when u assign G to w with the positional argument of 100. So it returns 10*100. Whereas, in the second code u just assign w_1 to the weight function with positional argument 10 which python interprets it to be for the place holder m and the argument for g is missing. Hence u got the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM