我在同一个类中有两个静态方法
class A:
@staticmethod
def methodA():
print 'methodA'
@staticmethod
def methodB():
print 'methodB'
Run Code Online (Sandbox Code Playgroud)
我怎么能打电话给methodA里面methodB?self似乎在静态方法中不可用.
小智 10
实际上,self静态方法不可用.如果使用装饰@classmethod而不是@staticmethod第一个参数,则会引用类本身(通常命名为cls).但尽管如此,在静态方法中,methodB()您可以methodA()直接通过类名访问静态方法:
@staticmethod
def methodB():
print 'methodB'
A.methodA()
Run Code Online (Sandbox Code Playgroud)
正如@Ismael Infante 所说,您可以使用@classmethod装饰器。
class A:
@staticmethod
def methodA():
print 'methodA'
@classmethod
def methodB(cls):
cls.methodA()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3593 次 |
| 最近记录: |