Pyking
Pyking

Reputation: 11

How to access class variable in method when class and class method have same variable with name also?

I am unable to access class variable in method of same class and my method also having same name of class variable

class x(object):
    x = 10    # class variable
    def method1(self,v1):
       x = v1   # method variable
       # here I want to access class variable

Upvotes: 0

Views: 108

Answers (2)

Sargam Modak
Sargam Modak

Reputation: 793

This code will help you understand the difference between class variable, instance variable and local variable.

class Test:
x = 10 //class variable or static variable; shared by all objects
def __init__(self):
    self.x = 20 //instance variable; different value for each object
def func(self, x): //method variable
    print Test.x
    print self.x
    print x

Output:
10
20
30
Test.x prints the static varible. To use instance variable you have to use self.instance_variable and you can directly use the local variable by its name inside the method.

Upvotes: 1

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

You need to do as follows! As Barmar mentioned, it isnt a good practice to use the same name for class and class variable!

>>> class x():
...     def method(self, v1):
...             self.x = v1
...             print self.x
...
>>> y = x()
>>> y.method(5)
5
>>> y.x
5

Upvotes: 0

Related Questions