Search code examples
classinstancepython-3.5static-methodsclass-method

How to access a class METHODS within static/class methods?


` class A(object): x = 0

def say_hi(self):
    pass

@staticmethod
def say_hi_static():
    pass

@classmethod
def say_hi_class(cls):
    pass

def run_self(self):
    self.x += 1
    print(self.x) # outputs 1
    self.say_hi()
    self.say_hi_static()
    self.say_hi_class()

@staticmethod
def run_static():
    print(A.x)  # outputs 0
    # A.say_hi() #  wrong
    A.say_hi_static()
    A.say_hi_class()

@classmethod
def run_class(cls):
    print (cls.x)# outputs 0
    # cls.say_hi() #  wrong
    cls.say_hi_static()
    cls.say_hi_class()

`

A.run_static() 0

A.run_class() 0 a=A()

a.run_class() 0

a.run_static() 0

Above code explain how to access class variable within static & class methods... What if I want to access methods' variable within static & class methods


Solution

  • You probably want to define the function mysub as a staticmethod, so you can use it as an "independent" function:

    class Myclass1(object):
        def __init__(self,d):#, dict_value):
            self.d=d
        def myadd(self):
            b=2
            return b
    
        @staticmethod
        def mysub(u):  #Note that self is not an argument!
            a=u
            print('A value:',a)
            return a     
    
    
    Instance=Myclass1(1)    # Created an instance
    Instance.mysub(1)
    
    # ('A value:', 1)
    # Out[42]: 1