当前位置: 移动技术网 > IT编程>脚本编程>Python > Python基于staticmethod装饰器标示静态方法

Python基于staticmethod装饰器标示静态方法

2020年10月17日  | 移动技术网IT编程  | 我要评论
英文文档:staticmethod(function)return a static method for function.a static method does not receive an i

英文文档:

staticmethod(function)

return a static method for function.

a static method does not receive an implicit first argument.

the @staticmethod form is a function decorator – see the description of function definitions in function definitions for details.

it can be called either on the class (such as c.f()) or on an instance (such as c().f()). the instance is ignored except for its class.

  标示方法为静态方法的装饰器

说明:

  1. 类中普通的方法,实际上既可以被类直接调用也可以被类的实例对象调用,但是被实例对象调用的时候,要求方法至少有一个参数,而且调用时会将实例对象本身传给第一个参数

>>> class student(object):
  def __init__(self,name):
    self.name = name
  def sayhello(lang):
    print(lang)
    if lang == 'en':
      print('welcome!')
    else:
      print('你好!')
 
  
>>> student.sayhello
<function student.sayhello at 0x02ac7810>
>>> a = student('bob')
>>> a.sayhello
<bound method student.sayhello of <__main__.student object at 0x02ad03f0>>
>>> student.sayhello('en') # 类调用的时候,将'en'传给了lang参数
en
welcome!

>>> a.sayhello() # 类实例对象调用的时候,将对象本身自动传给了lang参数,不能再接收参数
<__main__.student object at 0x02ad03f0>
你好!
  >>> a.sayhello('en')  traceback (most recent call last):  file "<pyshell#7>", line 1, in <module>  a.sayhello('en')  typeerror: sayhello() takes 1 positional argument but 2 were given

  2. staticmethod函数功能就是将一个方法定义成类的静态方法,正确的方法是使用 @staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。

# 使用装饰器定义静态方法
>>> class student(object):
  def __init__(self,name):
    self.name = name
  @staticmethod
  def sayhello(lang):
    print(lang)
    if lang == 'en':
      print('welcome!')
    else:
      print('你好!')

      
>>> student.sayhello('en') #类调用,'en'传给了lang参数
en
welcome!

>>> b = student('kim') #类实例对象调用,不再将类实例对象传入静态方法
>>> b.sayhello()
traceback (most recent call last):
 file "<pyshell#71>", line 1, in <module>
  b.sayhello()
typeerror: sayhello() missing 1 required positional argument: 'lang'

>>> b.sayhello('zh') #类实例对象调用,'zh'传给了lang参数
zh
你好!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网