使用类名调用Python静态方法更为常见,但对于长类名来说,这可能是一件令人头疼的事情。有时我在同一个类中使用self
来调用静态方法,因为我发现它看起来更干净
class ASomewhatLongButDescriptiveClassName:
def __init__(self):
# This works, but it's an eyesore
ASomewhatLongButDescriptiveClassName.do_something_static()
# This works too and looks cleaner.
self.do_something_static()
@staticmethod
def do_something_static():
print('Static method called.')
我的理解是,使用self
调用静态方法会被解释为ClassName.static_method(self)
,其中self
将被静态方法忽略。
EDIT-上述语句仅适用于实例方法:
我不应该使用self
调用同一类中的静态方法,有什么具体原因吗
FWIW This is a sister question to Difference between calling method with self and with class name?, which deals with non-static methods.
你做了一些不完全正确的陈述:
这并不常见,这是在课外进行的唯一方法。i、 e:
在本例中,
self.a_method()
不起作用,因为self
不会引用MyClass
的实例事实并非如此,例如:
self
只是指调用实例方法的类的实例(它有self
参数,甚至不必调用self
-不管调用第一个参数是什么,self
都是约定您可以在
self
上调用静态方法,因为self是具有静态方法的类的实例,因此具有该方法。您也可以直接在类上调用静态方法,因为静态方法不需要对象实例作为第一个参数-这是静态方法的要点在您喜欢的地方使用
self.a_method()
可以,但请记住self
将引用对象实例化为的类的对象,而不是您提到的特定类例如:
输出:
因此,您可以看到,从
self.
调用和从Class.
调用是有区别的相关问题 更多 >
编程相关推荐