1. 程式人生 > >python之內置裝飾器(property/staticmethod/classmethod)

python之內置裝飾器(property/staticmethod/classmethod)

類方法 nbsp 編譯器 簡單 用法 是把 test 打印 brush

python內置了property、staticmethod、classmethod三個裝飾器,有時候我們也會用到,這裏簡單說明下

1、property

作用:顧名思義把函數裝飾成屬性

一般我們調用類方法成員,都是如下寫法:

class propertyTest():
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def square(self):
        return self.x * self.y

pt = propertyTest(3,5)
print(pt.square())

這裏一看square就是類的一個方法,但如果把他寫成如下形式,那麽就不確定調用的一定是類方法:

class propertyTest():
    def __init__(self,x,y):
        self.x = x
        self.y = y

    @property
    def square(self):
        return self.x * self.y

pt = propertyTest(3,5)
print(pt.square)

這裏調用方法類似調用了一個成員變量一樣,如果寫成print(pt.square())編譯器會報錯

這就是property的用法, 把一個方法變成一個變量來調用

2、staticmethod

作用:不需要實例化,直接可以調用類中的方法,如下所示

class A():
    def __init__(self):
        pass

    @staticmethod
    def plus(x,y):
        print(x*y)

c = A()
c.plus(2,3)
A.plus(4,5)

我們可以實例化類A,然後調用方法plus,也可以直接類.方法調用

3、classmethod

作用:和staticmethod類似,不同的是把調用的類作為第一個參數傳入,如下:

class A():
    def __init__(self):
        pass

    @classmethod
    def plus(cls,x,y):
        print(cls)
        print(x*y)

A.plus(4,5)
c = A()
c.plus(5,6)

這裏print(cls)打印的是類A,其他用法同staticmethod

python之內置裝飾器(property/staticmethod/classmethod)