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

7
  • 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? Commented Mar 27, 2017 at 13:50
  • Why do you have mysub nested? Commented Mar 27, 2017 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 Commented Mar 27, 2017 at 13:51
  • 1
    You are acessing method of returned value, so In Your case its int Commented Mar 27, 2017 at 13:51
  • Possible duplicate of Accessing a function within a function(nested function?) Commented Mar 27, 2017 at 13:58

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.