+ 14
I dont understand that error
I think that a.,b are class variables. https://code.sololearn.com/cOrNOZfE8k8G/?ref=app
17 ответов
+ 3
Anonymous Guy Alexander Thiem I want the class variables line 3,4
+ 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)
+ 3
so a and b in line 3,4 are defaults for self.a and self.b?
+ 2
Variable within class are referred using self keyword. So instead of print(a) do print (self.a)
+ 2
If you add print(self.a) at the very beginning of the _init_ you see that those are exactly the same
+ 1
it works if you use self.a and self.b in _str_
+ 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
+ 1
Frogged Yes they seem to be defaults.
This can be seen through what I described in my previous comment....
+ 1
Yo class variable and instance variables are same in this case.
His instance variable is modifying class variable on initialization.
+ 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
+ 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
+ 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
+ 1
you can use myClass.a to access those variables....
- 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 :)
- 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 ☺