Pab*_*blo 76 python static-methods
当我有一个常规方法来调用类中的另一个方法时,我必须这样做
class test:
def __init__(self):
pass
def dosomething(self):
print "do something"
self.dosomethingelse()
def dosomethingelse(self):
print "do something else"
Run Code Online (Sandbox Code Playgroud)
但是当我有静态方法时,我无法写
self.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)
因为没有实例.我如何在Python中从同一个类的另一个静态方法调用静态方法?
编辑:多么糟糕.好的,我把问题编辑回原来的问题.我已经得到了Peter Hansen评论中第二个问题的答案.如果你认为我应该为我已经拥有的答案打开另一个问题,请告诉我.
war*_*iuc 108
我如何在Python中从同一个类的另一个静态方法调用静态方法?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
Run Code Online (Sandbox Code Playgroud)
jld*_*ont 69
class.method 应该管用.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
Run Code Online (Sandbox Code Playgroud)
Emi*_*tai 12
如果被调用的函数与调用者静态方法位于同一类中,则可以调用__class__.dosomethingelse()而不是。self.dosomethingelse()
class WithStaticMethods:
@staticmethod
def static1():
print("This is first static")
@staticmethod
def static2():
# WithStaticMethods.static1()
__class__.static1()
print("This is static too")
WithStaticMethods.static2()
Run Code Online (Sandbox Code Playgroud)
印刷:
This is first static
This is static too
Run Code Online (Sandbox Code Playgroud)
注意 - 看起来问题已经改变了一些.关于如何从静态方法调用实例方法的问题的答案是,如果不将实例作为参数传递或在静态方法中实例化该实例,则不能这样做.
以下内容主要是回答"如何从另一个静态方法调用静态方法":
请记住,有是在Python静态方法和类方法之间的差异.静态方法不使用隐式的第一个参数,而类方法将类作为隐式的第一个参数(通常cls按惯例).考虑到这一点,以下是您将如何做到这一点:
如果它是静态方法:
test.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)
如果是类方法:
cls.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)
好的,类方法和静态方法之间的主要区别是:
| 归档时间: |
|
| 查看次数: |
83886 次 |
| 最近记录: |