如何在 static/class 方法中访问 class 方法?
How to access a class METHODS within static/class methods?
`
class 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
以上代码解释了如何在静态和 class 方法中访问 class 变量...
如果我想在静态和 class 方法中访问方法的变量怎么办
您可能想将函数 mysub 定义为 staticmethod,这样您就可以将其用作 "independent" 函数:
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
` class 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
以上代码解释了如何在静态和 class 方法中访问 class 变量... 如果我想在静态和 class 方法中访问方法的变量怎么办
您可能想将函数 mysub 定义为 staticmethod,这样您就可以将其用作 "independent" 函数:
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