Reputation: 481
I understand in Python a class can have a class variable (shared among all objects), and also a unique object variable (which is uniquely assignable from object to object).
However, why do I get a 'object has no attribute 'nObjVar' error, when I try to access that object's variable from another function?
class TestClass:
nClassVar1 = 0 #Class Var shared across all objects
def __init__(self, defaultInitVal = 0):
nObjVar = defaultInitVal #Object Var Only
def MyFuncMult(self):
result = nObjVar * 10;
return ( result )
Upvotes: 0
Views: 62
Reputation: 3186
To make a variable available to all methods in a class, save it in the self
namespace.
class TestClass:
nClassVar1 = 0 #Class Var shared across all objects
def __init__(self, defaultInitVal = 0):
self.nObjVar = defaultInitVal #Object Var Only
def MyFuncMult(self):
result = self.nObjVar * 10;
return ( result )
Upvotes: 2
Reputation: 378
The reason is because you are defining it as a local variable in the init, if you want it to be a member of the object you need to type
self.nObjVar
this will set it to a member
Upvotes: 2