天天看點

Python中的@staticmethod,@classmethod,self,cls到底是什麼意思?普通類方法使用@staticmethod 和@classmethod 方法修飾self和cls以及@staticmethod 和@classmethod修飾的差別

普通類方法

在Python中,通常我們調用某個類的方式,首先要執行個體化一個對象才能調用該類的方法,比如:

# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

# 執行個體化一個對象
LiMing = People()
LiMing.hello()

"""""""""""""""""""""
輸出:hello everyone
"""""""""""""""""""""
           

使用@staticmethod 和@classmethod 方法修飾

當我們使用@staticmethod 和@classmethod 修飾後,則不需要執行個體化就可以直接調用類方法,下面舉例說明:

# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

    @staticmethod
    def say_morning():
        print("good morning")

    @classmethod
    def say_afternoon(cls):
        print("good afternoon")


# 執行個體化一個對象
LiMing = People()
LiMing.hello()
# 使用@staticmethod 或者使用@classmethod 不需要執行個體化就可以直接調用類方法
People.say_morning()
People.say_afternoon()

"""""""""""""""""""
這裡是輸出:
hello, Everyone.
good morning
good afternoon
"""""""""""""""""""
           

self和cls以及@staticmethod 和@classmethod修飾的差別

使用@staticmethod 和@classmethod 都不需要執行個體化就可以直接調用類方法,但是兩者還是有差別的,我們知道:

  • @staticmethod:不需要表示對象的self和自身類的clas參數,就和使用函數一樣
  • @classmethod:不需要self,但第一個參數需要是表示自身類的cls參數。

    使用表示自身的cls參數之後,@classmethod裝飾的函數就可以使用類本身的方法。下面我們舉例進行說明:

# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

    @staticmethod
    def say_morning():
        print("good morning")
        # print(People.hello())  這裡會報錯!

    @classmethod
    def say_afternoon(cls):
        print("good afternoon")
        print(cls().hello())


# 執行個體化一個對象
LiMing = People()
LiMing.hello()

People.say_morning()
People.say_afternoon()

"""""""""""""""""""
這裡是輸出:
hello, Everyone.
good morning
good afternoon
hello, Everyone.
"""""""""""""""""""