zoukankan      html  css  js  c++  java
  • python 中 staticmethod 和 classmethod有什么区别

    面试中经常会问到staticmethod 和 classmethod有什么区别?

    首先看下官方的解释:

    staticmethod:

    class staticmethod

    staticmethod(function) -> method

    Convert a function to be a static method.

    A static method does not receive an implicit first argument. To declare a static method, use this idiom:

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

    It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.

    Static methods in Python are similar to those found in Java or C++. For a more advanced concept, 

    它的一个作用就是将一个一个类的函数转为一个静态函数。静态函数的作用和java,c++的静态函数类似,作用一些全局变量等。

    classmethod:

    class classmethod

    classmethod(function) -> method

    Convert a function to be a class method.

    A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

    class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f)

    It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

    Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

    classmethod 和 c++,java的类方法不同。类方法的参数是一个类,实例方法的参数是一个实例。

    例如下面的程序:

    class A:
        @staticmethod
        def a():
            print "this is a"
    
        @classmethod
        def b(rty):
            print(rty)
            print "this is b"
    
    testa = A()
    testa.a()
    testa.b()
    
    # 输出为:
    # this is a
    # __main__.A
    # this is b

    其中的__main__.A 为类A的名字。

    如果将@classmethod去掉,则输出的结果为:

    class A:
        @staticmethod
        def a():
            print "this is a"
    
    #    @classmethod
        def b(rty):
            print(rty)
            print "this is b"
    
    testa = A()
    testa.a()
    testa.b()
    
    # 输出为:
    # this is a
    # <__main__.A instance at 0x1070f03f8>
    # this is b

    可以看到这个时候rty的内容为,类A实例的地址。它和c++的类方法不是一回事儿,c++,java的类方法必须通过实例来调用。

  • 相关阅读:
    检测登录按钮 ,回车即登录
    [转]程序变量命名推荐规范
    [NET].NET Framework 3.5 SP1 真正的离线安装(转)
    Arthas使用教程[转载]
    Python中Hamcrest断言的使用
    C#中查询不支持中文的解决方法
    如何防止C#的小黑窗关闭
    AWS的EC2 micro instance真是慢啊
    一键分享文字图片到新浪微博,facebook,twitter 还有保存打印等 (使用 iOS6 自带的 social.framework)
    自己写的可以布置多个button在同一行的ActionSheet (iPhone)
  • 原文地址:https://www.cnblogs.com/Spider-spiders/p/12004958.html
Copyright © 2011-2022 走看看