詳細内容
Python類所包含的最重要的兩個成員就是變量和方法,其中類變量屬于類本身,用于定義該類本身所包含的狀态資料:而執行個體變量則屬于該類的對象,用于定義對象所包含的狀态資料:方法則用于定義該類的對象的行為或功能實作。
對于Python類中,方法的定義方式,我們可以歸納有4種類型:推薦學習:Python視訊教程)
1、不帶self、cls參數且不加裝飾器(staticmethod、classmethod)
定義代碼如下:class Student(object):
def func(name):
print('my name is {}'.format(name))
2、正常的方法定義,帶self參數
定義代碼如下:class Student(object):
def func(self, name):
print('my name is {}'.format(name))
3、類方法:加裝飾器(classmethod)
定義代碼如下:class Student(object):
@classmethod
def func(cls, name):
print('my name is {} from {}'.format(name, cls.__name__))
靜态方法:加裝飾器(staticmethod)
定義代碼如下:class Student(object):
@staticmethod
def func(name):
print('my name is {}'.format(name))
更多Python相關技術文章,請通路Python教程欄目進行學習!