如何在静态/类方法中访问类METHODS?

时间:2017-03-27 13:46:33

标签: class instance python-3.5 static-methods class-method

` A类(对象):     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

    
  

上面的代码解释了如何在static&中访问类变量。班级方法......    如果我想访问static&中的方法变量怎么办?课程方法

1 个答案:

答案 0 :(得分:1)

您可能希望将函数mysub定义为staticmethod,因此您可以将其用作"独立的"功能:

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