Python静态方法和类方法区别?

发布时间:2022-04-18 09:49:19 人气:147 作者:多测师

  尽管 classmethod 和 staticmethod 非常相似,但在用法上依然有一些明显的区别。classmethod 必须有一个指向类对象的引用作为第一个参数,而 staticmethod 可以没有任何参数。

  举个栗子:

  class Num:

  # 普通方法:能用Num调用而不能用实例化对象调用

  def one():

  print ('1')

  # 实例方法:能用实例化对象调用而不能用Num调用

  def two(self):

  print ('2')

  # 静态方法:能用Num和实例化对象调用

Python静态方法和类方法区别?

  @staticmethod

  def three():

  print ('3')

  # 类方法:第一个参数cls长什么样不重要,都是指Num类本身,调用时将Num类作为对象隐式地传入方法

  @classmethod

  def go(cls):

  cls.three()

  Num.one() #1

  #Num.two() #TypeError: two() missing 1 required positional argument: 'self'

  Num.three() #3

  Num.go() #3

  i=Num()

  #i.one() #TypeError: one() takes 0 positional arguments but 1 was given

  i.two() #2

  i.three() #3

  i.go() #3

  以上内容为大家介绍了Python静态方法和类方法区别?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线