python-類: 靜態方法(staticmethod)、類方法(classmethod)和實例方法


前言

python類中方法有三種:靜態方法(staticmethod)、類方法(classmethod)、實列方法。

本文主要介紹下靜態方法(staticmethod)和類方法(classmethod)。

使用(fake)

class TestFuc(object):
    def instance_fuc(self, x):
        print('instance_fuc(%s,%s)' % (self, x))

    @classmethod
    def class_fuc(cls,x):
        print('class_fuc(%s,%s)' % (cls,x))

    @staticmethod
    def static_fuc(x):
        print('static_fuc(%s)' % x)


test_fuc = TestFuc()

# 實例方法
test_fuc.instance_fuc(1)
# 類方法
test_fuc.class_fuc(1)
TestFuc.class_fuc(1)

# 靜態方法
test_fuc.static_fuc(1)
TestFuc.static_fuc(1)

  

應用

脫離了實際的應用場景,談使用就是是耍流氓。上文介紹的"使用"僅僅展示如何定義(進入)和偽使用,真正的場景不會這樣用的。

靜態方法(staticmethod)和類方法(classmethod)並不常用。我喜歡在stackoverflow:What is the advantage of using static methods in Python?的一句話:"So they aren't useful for day-to-day methods"。盡管如此,我們依然要學習,並熟悉使用(原因:語言特性的完整、特殊場景的使用)。

目前,我看到網上介紹比較多應用用它們作為構造函數。

# staticmethod實現
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now(): #用Date.now()的形式去產生實例,該實例用的是當前時間
        t=time.localtime() #獲取結構化的時間格式
        return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建實例並且返回
    @staticmethod
    def tomorrow():#用Date.tomorrow()的形式去產生實例,該實例用的是明天的時間
        t=time.localtime(time.time()+86400)
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

a=Date('1987',11,27) #自己定義時間
b=Date.now() #采用當前時間
c=Date.tomorrow() #采用明天的時間

print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)

  

繼承類中的區別

  • 子類的實例繼承了父類的static_method靜態方法,調用該方法,還是調用的父類的方法和類屬性。
  • 子類的實例繼承了父類的class_method類方法,調用該方法,調用的是子類的方法和子類的類屬性。
class Foo(object):
    X = 1
    Y = 2

    @staticmethod
    def averag(*mixes):
        return sum(mixes) / 1

    @staticmethod
    def static_method():
        return Foo.averag(Foo.X, Foo.Y)

    @classmethod
    def class_method(cls):
        return cls.averag(cls.X, cls.Y)


class Son(Foo):
    X = 3
    Y = 5

    @staticmethod
    def averag(*mixes):
        return sum(mixes) / 2

p = Son()
print(p.static_method())
print(p.class_method())

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM