Python的静态类方法调用

python的类方法需要类作为第一个参数传入。通常用cls作为变量名字。而静态方法不需要self参数。并且它们在经典类和新式类中都可以调用。

class TestStaticMethod(object):
@staticmethod
def foo():
print ‘calling static method…’

class TestClassMethod(object):
@classmethod
def foo(cls):
print ‘the class’, cls.__name__, ‘is calling the class method foo()..’

In [7]: TestClassMethod.foo()
the class TestClassMethod is calling the class method foo()..

——————————–
In [8]: TestStaticMethod.foo()
calling static method…

——————————–
In [9]: a = TestStaticMethod()

In [10]: a.foo()
calling static method…

——————————–
In [10]: a.foo()
calling static method…

——————————–
In [11]: b = TestClassMethod()

In [12]: b.foo()
the class TestClassMethod is calling the class method foo()..

可见,在对象和实例中都可以调用。

In [15]: class C(TestStaticMethod):
….: pass
….:

In [16]: C.foo()
calling static method…

——————————-

In [17]: c = C()

In [18]: c.foo()
calling static method…

——————————-
In [19]: class D(TestClassMethod):
….: pass
….:

In [20]: D.foo()
the class D is calling the class method foo()..

——————————-
In [21]: d = D()

In [22]: d.foo()
the class D is calling the class method foo()..

在子类中仍然可就调用。类名会自动通过cls变量传入




Related posts

此条目发表在 Python 分类目录,贴了 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已被标记为 *

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>