I come from java background, so I am slightly confused here.
Consider the code snippet below:
class A():
def __init__(self, **kwargs):
self.obj_var = "I am obj var"
@classmethod
def class_method(cls):
print cls.obj_var # this line is in question here
cls.cls_obj = "I m class object"
return cls.cls_obj
This throws an error :
In [30]: a = A()
In [31]: a.obj_var
Out[31]: 'I am obj var'
In [32]: a.class_method()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-3dcd9d512548> in <module>()
----> 1 a.class_method()
<ipython-input-29-9c0d341ad75f> in class_method(cls)
8 @classmethod
9 def class_method(cls):
---> 10 print cls.obj_var
11 cls.cls_obj = "I m class object"
12 return cls.cls_obj
AttributeError: class A has no attribute 'obj_var'
iIf I comment out @classmethod
, this will work fine.
My understanding (which is incorrect m sure) :
When I do a = A()
, then all the variables(obj_var
) created in __init__
can be accessed via this a
when passed to any other classmethod
of same class.Apparently this is not the case.
Question(s)
why am i not able to access
__init__
var
s inclass_method
when decorater@classmethod
is mentioned in the method but on removing the decorater, it works fine?how python internally process this particular class upon compilation?
is there any way i can use
@classmethod
and the__init__
vars in same method?