Can you please explain the output of this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Can you please explain the output of this code?

class FirstClass: n = 4 def__init__(self,n): n = n//4 a = FirstClass(8) print(a.n) Answer is 4

7th Mar 2020, 10:40 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
5 Answers
+ 4
The n variable in the class is defined before the __init__ method and has no self prefix. So it's a class attribute and all objects of the class have access to it. On the other hand in the __init__ the n is defined without self and so it has no effect on n copy of objects. So we'll have n=4 for all objects.
7th Mar 2020, 6:38 PM
Qasem
+ 4
Hi Quote: " 1 class FirstClass: 2 n = 4 3 def__init__(self,n): 4 n = n//4 5 a = FirstClass(8) 6 print(a.n) Answer is 4" Explanation with numbered lines: At line 2, you define a class variable n & initialize/assign it the value 4. Then in constructor, line 3, you define an instance variable (or parameter) n, so another variable n. What constructor does is, line 4 it sets this last instance variable n to its own value divided by 4. But it doesn't affect the class variable n which has the value 4. So at line 5, when you create an instance called a of your class receiving 8 as instance variable / parameter, the class variable a.n is initialized with value 4 and is NOT affected by the code in constructor (line 4). Only the instance variable n is set to 8/4 = 2. Finally, line 6 when you print the class variable a.n value, you get 4 which is fairly logical. Here is your code updated with renamed class variable & self at line 4 to properly affect your class variable: 1 class FirstClass: 2 myN = 4 3 def__init__(self,n): 4 self.myN = n//4 5 a = FirstClass(8) 6 print(a.myN) Answer is now 2 as our class variable was updated. I hope it helps. All the best for your Python classes learning. P.S.: You should be able to find more detailed info on class & instance variables in Python tutorial here on SoloLearn. Otherwise, I found this tutorial on digitalocean that explains & shows clear examples of both kinds of variables: https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3#class-variables
7th Mar 2020, 7:15 PM
Tom BWDEV 🇺🇦
Tom BWDEV 🇺🇦 - avatar
+ 3
Tom BWDEV it will be more useful to see more answers.
7th Mar 2020, 7:21 PM
Qasem
+ 2
Qasem, sorry didn't see your answer as I was typing mine. You're right too.
7th Mar 2020, 7:19 PM
Tom BWDEV 🇺🇦
Tom BWDEV 🇺🇦 - avatar
+ 2
Qasem, hopefully & there is the short answer & the long answer, depending on what the users want lol.
7th Mar 2020, 7:28 PM
Tom BWDEV 🇺🇦
Tom BWDEV 🇺🇦 - avatar