1. 程式人生 > 程式設計 >Python基於staticmethod裝飾器標示靜態方法

Python基於staticmethod裝飾器標示靜態方法

英文文件:

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>",in <module>
  b.sayHello()
TypeError: sayHello() missing 1 required positional argument: 'lang'

>>> b.sayHello('zh') #類例項物件呼叫,'zh'傳給了lang引數
zh
你好!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。