how to access n in this code from change method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how to access n in this code from change method?

class Myclass: n=0 def change(self,val): n=val ke=Myclass() ke.change(2) print(ke.n) '''here output is 0 but i want output =2 ,how can we do that'''

28th Aug 2018, 8:40 PM
Meet Rajpopat
Meet Rajpopat - avatar
4 Answers
+ 2
Two ways: 1. Using 'self' ------------------- class MyClass: n = 0 def change(self, val): self.n = val 2. Using the class name: ------------------------------------- class MyClass: n = 0 def change(self, val): MyClass.n = val EDITED: ====== Anna is right! Actually the first way I showed will not access the 'n', it will create another one in the instance.
28th Aug 2018, 8:52 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 2
Markus Kaleton bro your method is right but ,just by putting self.n in my code in change method we can get access through it.. sorry but i just realize after posting it😅😅
28th Aug 2018, 8:53 PM
Meet Rajpopat
Meet Rajpopat - avatar
+ 2
n is a class variable in this case, not an instance variable. If you change it, it will be changed for every Myclass object. If you're sure that that's what you want to do, you can access it with self.__class__.n in change().
28th Aug 2018, 8:53 PM
Anna
Anna - avatar
28th Aug 2018, 8:45 PM
Markus Kaleton
Markus Kaleton - avatar