0

` 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

Abhishek
  • 471
  • 5
  • 17
  • You can't. You are confusing aspects of classes (which have methods associated with them, which you can access with the "dot" syntax) and functions (whose inner functions are literally private to them). However, I think that there is no reason for you to have nested `mysub` inside of `myadd` here. What are you trying to do? – Andrew Jaffe Mar 27 '17 at 13:50
  • Why do you have `mysub` nested? – Moses Koledoye Mar 27 '17 at 13:50
  • I'm pretty sure it's similar to the way local variables work. The `mysub` function is only defined for the purpose of the `myadd` function and only exists there – AsheKetchum Mar 27 '17 at 13:51
  • 1
    You are acessing method of returned value, so In Your case its int – Take_Care_ Mar 27 '17 at 13:51
  • Possible duplicate of [Accessing a function within a function(nested function?)](http://stackoverflow.com/questions/7054228/accessing-a-function-within-a-functionnested-function) – Take_Care_ Mar 27 '17 at 13:58
  • Please use markdown syntax. – Andrew Jaffe Mar 27 '17 at 15:10
  • Sorry, Will use markdown from next time – Abhishek Mar 27 '17 at 15:33

1 Answers1

1

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
FLab
  • 7,136
  • 5
  • 36
  • 69