ben
ben

Reputation: 481

Can 2 functions access an object variable in Python

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

Answers (3)

neodelphi
neodelphi

Reputation: 2786

Try self.nObjVar to reference the variable of the instance.

Upvotes: 1

Andrew Johnson
Andrew Johnson

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

cujo
cujo

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

Related Questions