+ 2

I would appreciate if someone can explain this step by step.

This code will print 1234. I tried to understand how the argument is passed around, but it is not clear. I kinda understand, which also means I kinda don't understand. ###################### class phone: def __init__(self, number): self.number = number number = 1111 ppl = phone(1234) print(ppl.number)

31st Oct 2017, 10:59 AM
John S.R. LEE
John S.R. LEE - avatar
4 Answers
+ 14
The object ppl belongs to the phone class thus its constructor accepts a parameter "number". You pass the value 1234 which becomes a property of the object with self.number=number and you modify "number" AFTERWARDS thus its initial value does not change to 1111...
31st Oct 2017, 11:27 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 8
What's probably confusing you is the 'self' special argument... If the Python Sololearn course fail to help you, maybe try this link: https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/
31st Oct 2017, 12:42 PM
visph
visph - avatar
+ 5
Upon recent reading (I'm also learning Python) I found that in order to achieve the effect similar to "pass by reference" the argument passed into the method/function parameter needs to be an immutable type, apparently, in Python int and string are immutables, hence the change in your method for <number> parameter is not reflected on the method caller space. Source: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference (Answer from a member by the name Raymond Hettinger seems clear enough)
31st Oct 2017, 1:57 PM
Ipang
1st May 2018, 9:32 PM
Johannes
Johannes - avatar