python中常用的內建裝飾器

來源:互聯網
上載者:User
@property

使調用類中的方法像引用類中的欄位屬性一樣。被修飾的特性方法,內部可以實現處理邏輯,但對外提供統一的調用方式。遵循了統一訪問的原則。

樣本:

# coding: utf-8class TestClass:    name = "test"    def __init__(self, name):        self.name = name    @property    def sayHello(self):        print "hello", self.namecls = TestClass("felix")print "通過執行個體引用屬性"print cls.nameprint "像引用屬性一樣調用@property修飾的方法"cls.sayHello

輸出結果:

通過執行個體引用屬性felix像引用屬性一樣調用@property修飾的方法hello felix

此外,@property可以用來實作類別似與Java中set和get方法 @staticmethod

將類中的方法裝飾為靜態方法,即類不需要建立執行個體的情況下,可以通過類名直接引用。到達將函數功能與執行個體解除綁定的效果。

樣本:

# coding: utf-8class TestClass:    name = "test"    def __init__(self, name):        self.name = name    @staticmethod    def fun(self, x, y):        return  x + ycls = TestClass("felix")print "通過執行個體引用方法"print cls.fun(None, 2, 3) # 參數個數必須與定義中的個數保持一致,否則報錯print "類名直接引用靜態方法"print TestClass.fun(None, 2, 3) # 參數個數必須與定義中的個數保持一致,否則報錯

輸出結果:

通過執行個體引用方法5類名直接引用靜態方法5
@classmethod

類方法的第一個參數是一個類,是將類本身作為操作的方法。類方法被哪個類調用,就傳入哪個類作為第一個參數進行操作。

執行個體:

# coding: utf-8class Car(object):    car = "audi"    @classmethod    def value(self, category): # 可定義多個參數,但第一個參數為類本身        print "%s car of %s" % (category, self.car)class BMW(Car):    car = "BMW"class Benz(Car):    car = "Benz"print "通過執行個體調用"baoma = BMW()baoma.value("Normal") # 由於第一個參數為類本身,調用時傳入的參數對應的時categoryprint "通過類名直接調用"Benz.value("SUV")

輸出結果:

通過執行個體調用Normal car of BMW通過類名直接調用SUV car of Benz

注意,靜態方法和類方法是為類操作準備的。雖然通過執行個體也能調用,但是不建議。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.