zoukankan      html  css  js  c++  java
  • @staticmethod

    python staticmethod 返回函数的静态方法。

    该方法不强制要求传递参数,如下声明一个静态方法:

    class C(object):
        @staticmethod
        def f(arg1, arg2, ...):
            ...

    以上实例声明了静态方法 f,从而可以实现实例化使用 C().f(),当然也可以不实例化调用该方法 C.f()。

    函数语法

    staticmethod(function)

    参数说明:

    实例

     
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class C(object):
        @staticmethod
        def f():
            print('runoob');
     
    C.f();          # 静态方法无需实例化
    cobj = C()
    cobj.f()        # 也可以实例化后调用

    以上实例输出结果为:

    runoob
    runoob

    staticmethod 参数要求是 Callable, 也就是说 Class 也是可以的:

    class C1(object):
        @staticmethod
        class C2(object):
            def __init__(self, val = 1):
                self.val = val
            def shout(self):
                print("Python世界第%d!"%self.val)
    tmp = C1.C2(0)
    print(type(tmp))    # 输出 : <class '__main__.C1.C2'>
    tmp.shout()         # 输出 : Python世界第0!
     
  • 相关阅读:
    自我介绍 Self Introduction
    HDU1864 最大报销额
    HDU2955 Robberies
    Sicily 1509. Rails
    Sicily 1031. Campus
    Sicily 1090. Highways
    Sicily 1034. Forest
    Sicily 1800. Sequence
    Sicily 1150. 简单魔板
    CodeVS4919 线段树练习4
  • 原文地址:https://www.cnblogs.com/tingtin/p/13614978.html
Copyright © 2011-2022 走看看