0

Python function: from where does it get value?

def f(a, x): # a.x=2, x=3 return a.x + x # 5 class A: def f(self, x): # input x = 2 self.x = x # a.x property = 2 return x + 1 # 2+1=3 a = A() # x not yet exists, a = obj y = f(a, a.f(2)) # after comma: 3 print(y) # output = 5 When debugging this SL challenge, I found that a = 2 in the FIRST LINE. Anyone to explain why? I have commented the code for easier understanding.

19th Feb 2020, 7:28 AM
Prof. Dr. Zoltán Vass
5 Réponses
+ 1
y = f(a, a. f(2)) calls method f of a and assigns 2 to attribute x That is done before calling free function f.
19th Feb 2020, 7:38 AM
Oma Falk
Oma Falk - avatar
+ 1
at the moment you call the free function f a has an attribute x=2. So first parameter is a with a. x = 2. 2nd parameter is a.f(2) which has a kind of side effect. It a) returns 3 and b) assigns 2 to a.x inner before outer, so assignment is done before calling free f.
19th Feb 2020, 8:16 AM
Oma Falk
Oma Falk - avatar
+ 1
Oma Falk Now it is clear. I have missed side effect “b”. Thanks again and have a great day!
19th Feb 2020, 9:15 AM
Prof. Dr. Zoltán Vass
0
Oma Falk Thanks! You have helped me clarifying my question. What is not clear for me: calling function f here y = f(a, a.f(2)) ... assigns 2 to “a.x” and not to “a”. In the first line, the function f gets “a” attribute and not a.x This is my real question.
19th Feb 2020, 8:01 AM
Prof. Dr. Zoltán Vass
0
ok but it uses a.x fir return
19th Feb 2020, 8:07 AM
Oma Falk
Oma Falk - avatar