+ 14

I dont understand that error

I think that a.,b are class variables. https://code.sololearn.com/cOrNOZfE8k8G/?ref=app

9th Oct 2020, 5:03 PM
Oma Falk
Oma Falk - avatar
16 Respostas
+ 3
‎ ‏‏‎Anonymous Guy Alexander Thiem I want the class variables line 3,4
9th Oct 2020, 5:08 PM
Oma Falk
Oma Falk - avatar
+ 3
Class variable are referred using self and function arguments can be referred directly Eg. class A: b= 0 def somefun(self, x): print(self.b) print (x)
9th Oct 2020, 5:10 PM
‎ ‏‏‎Anonymous Guy
+ 3
so a and b in line 3,4 are defaults for self.a and self.b?
9th Oct 2020, 5:20 PM
Oma Falk
Oma Falk - avatar
+ 2
Variable within class are referred using self keyword. So instead of print(a) do print (self.a)
9th Oct 2020, 5:05 PM
‎ ‏‏‎Anonymous Guy
+ 2
If you add print(self.a) at the very beginning of the _init_ you see that those are exactly the same
9th Oct 2020, 5:11 PM
Alexander Thiem
Alexander Thiem - avatar
+ 1
it works if you use self.a and self.b in _str_
9th Oct 2020, 5:06 PM
Alexander Thiem
Alexander Thiem - avatar
+ 1
Frogged you won't get output as 1. When you create an object, constructor is called and it modifies value of both a and b to 2 and they are modifying the same variable declared at line 3, 4
9th Oct 2020, 5:16 PM
‎ ‏‏‎Anonymous Guy
+ 1
Frogged Yes they seem to be defaults. This can be seen through what I described in my previous comment....
9th Oct 2020, 5:23 PM
Alexander Thiem
Alexander Thiem - avatar
+ 1
Yo class variable and instance variables are same in this case. His instance variable is modifying class variable on initialization.
9th Oct 2020, 5:27 PM
‎ ‏‏‎Anonymous Guy
+ 1
Nikhil what you are doing is creating new instance of class without running constructor and using its variables. Idk if it a correct approach
9th Oct 2020, 5:36 PM
‎ ‏‏‎Anonymous Guy
+ 1
nihil let's not forget a=2 and b=2 is hard coded into constructor and there is no way to change them during initialization. So Calling them instance variable would be wrong. They are not unique to any instance
9th Oct 2020, 5:43 PM
‎ ‏‏‎Anonymous Guy
+ 1
In that case, I think this implementation is wrong. Why modify class variables in constructor when there is a need to access class variable later on
9th Oct 2020, 5:48 PM
‎ ‏‏‎Anonymous Guy
+ 1
you can use myClass.a to access those variables....
9th Oct 2020, 6:16 PM
Alexander Thiem
Alexander Thiem - avatar
10th Oct 2020, 3:26 PM
Alexander Thiem
Alexander Thiem - avatar
- 1
For the function the variable a is not defined ! And it's normal because you have to write "self.a" to bind it with the object attribute :)
10th Oct 2020, 10:27 PM
Saifeddine_boughanmi
Saifeddine_boughanmi - avatar
- 1
Frogged https://code.sololearn.com/c3MX0bD6CLih/?ref=app try referring the class variables with self.<variable name>. I edited ur code so check out my solution ☺
12th Oct 2020, 8:38 AM
Frank Owusu Boakye
Frank Owusu Boakye - avatar