从 class 内部调用静态方法
calling static method from inside the class
从class(包含静态方法)内部调用静态方法时,可以通过以下方式完成:
Class.method() 或 self.method()
有什么区别?
每个的独特用例是什么?
class TestStatic(object):
@staticmethod
def do_something():
print 'I am static'
def use_me(self):
self.do_something() # 1st way
TestStatic.do_something() # 2nd way
t = TestStatic()
t.use_me()
打印
I am static
I am static
我认为 TestStatic.do_something()
更好,因为它展示了对静态成员的理解。静态成员是属于 class 的对象和在 class 上调用的方法,在大多数情况下,它们是实用程序 class。因此,通过class调用该方法更为合适。
通过使用 TestStatic.do_something()
,您将绕过子类上的任何重写:
class SubclassStatic(TestStatic):
@staticmethod
def do_something():
print 'I am the subclass'
s = SubclassStatic()
s.use_me()
将打印
I am the subclass
I am static
这可能是您想要的,也可能不是。选择最符合您期望的方法。
从class(包含静态方法)内部调用静态方法时,可以通过以下方式完成:
Class.method() 或 self.method()
有什么区别?
每个的独特用例是什么?
class TestStatic(object):
@staticmethod
def do_something():
print 'I am static'
def use_me(self):
self.do_something() # 1st way
TestStatic.do_something() # 2nd way
t = TestStatic()
t.use_me()
打印
I am static
I am static
我认为 TestStatic.do_something()
更好,因为它展示了对静态成员的理解。静态成员是属于 class 的对象和在 class 上调用的方法,在大多数情况下,它们是实用程序 class。因此,通过class调用该方法更为合适。
通过使用 TestStatic.do_something()
,您将绕过子类上的任何重写:
class SubclassStatic(TestStatic):
@staticmethod
def do_something():
print 'I am the subclass'
s = SubclassStatic()
s.use_me()
将打印
I am the subclass
I am static
这可能是您想要的,也可能不是。选择最符合您期望的方法。