面试中经常会问到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的类方法必须通过实例来调用。

最新文章

  1. WPF menu
  2. matlab画柱状图
  3. SpringMVC 的RequestMapping
  4. 阿里云ecs Linux下安装MySQL后设置root密码 【转】
  5. Struts2中 Result类型配置详解
  6. RO05 - 如何编写RemObjects SDK服务端 (Delphi Version)
  7. js运算之比较大小
  8. SSH由WAS/Tomcat/Weblogic迁移到JBOSS
  9. dedecms5.7安装百度(ueditor)编辑器的方法
  10. linux路由配置负载均衡
  11. HDU-4336 Card Collector 概率DP
  12. Live555类结构
  13. ACM比赛(第三次D)
  14. hdu_5773_The All-purpose Zero(LIS)
  15. vue实现图书管理demo
  16. Open-Falcon第七步安装报警模块(小米开源互联网企业级监控系统)
  17. 13_Android的生命周期
  18. Path Analyzer Pro出现raw socket问题
  19. 从零开始学安全(五)●Vmware虚拟机三种网络模式详解
  20. Entity Framework框架 (二)

热门文章

  1. Codeforces Round #511 (Div. 2) C. Enlarge GCD (质因数)
  2. Linux网络编程综合运用之MiniFtp实现(五)
  3. Django2-settings常用配置
  4. HaspMap和ConcurrentHashMap
  5. LOJ P10150 括号配对 题解
  6. 后台(一)vue+element-ui(全局配置)
  7. Oracle Linux 6.4 LVM中误删VG之恢复过程
  8. [Luogu] 送花
  9. P1021 邮票面值设计——搜索+完全背包
  10. Fidller抓包分析post请求