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())

#"""

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