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

2 answers

  • answered 2018-02-13 03:45 Keerthana Prabhakaran

    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
    

  • answered 2018-02-13 05:39 Sargam Modak

    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.