python入門:靜態方法、類成員方法



若有幫助到你,記得點贊哦!

參考:python基礎教程第二版 Hetland

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 09:52:45 2018

@author: Lelouch_C.C
"""

#"""
class MyClass:
    def smeth():
        print('lalala...')
    smeth=staticmethod(smeth)  #靜態方法的定義沒有self參數,且能夠被類本身直接調用
    
    def cmeth(cls):
        print('hahaha...')  
    cmeth=classmethod(cmeth)  #類成員方法定義了cls,類似於self,類成員方法可以直接用類的具體對象調用
print(MyClass.smeth())
print(MyClass.cmeth())

#"""
"""
class MyClass:
    @staticmethod   
    # @操作符在方法或函數上方將裝飾器列出,可指定多個裝飾器,多個裝飾器在應用時的順序與指定順序相反
    def smeth():
        print('lalala...')
   #靜態方法
    @classmethod
    def cmeth(cls):
        print('hahaha...')  
    #類成員方法

print(MyClass.smeth())
print(MyClass.cmeth())

#"""

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章