【Python】-【類解析】--【指令碼執行個體】

來源:互聯網
上載者:User

標籤:style   icm   ted   --   cal   turn   構造   替代   env   

通過指令碼案例,解析下Python中類的幾個概念在指令碼中的應用

指令碼如下:

++++++++++++++++++++++++++++++++++++++++

#!/usr/bin/env python
#-*- coding: utf8 -*-

class MyClass(object):  #定義類

    message = "Hello, Developer"        #定義類的成員變數   

    def show(self):     #類中的成員函數,必須帶參數self
        print self.message
        print "Here is %s in %s!"  % (self.name,self.color)

    @staticmethod       #定義靜態函數裝飾器
    def PrintMessage(): #定義靜態函數,可以通過類名直接調用
        print "printMessage is called"
        print MyClass.message

    @classmethod        #定義類函數裝飾器
    def createObj(cls, name, color):    #定義類函數,可以通過類名直接調用;第一個參數必須為:隱性參數,替代類名本身
        print "Object will be created: %s(%s, %s)" % (cls.__name__, name, color)
        return cls(name, color)

    def __init__(self, name = "unset", color = "black"):        #定義建構函式
        print "Constructor is called with params: ",name, " ", color
        self.name = name        # 定義執行個體成員變數
        self.color = color

    def __del__(self):  #定義解構函式:建構函式的反函數
        print "Destructor is called for %s!" % self.name

#通過類名來訪問:靜態函數和類函數
MyClass.PrintMessage()

inst = MyClass.createObj("Toby", "Red")
print inst.message
del inst

輸出結果:

printMessage is called
Hello, Developer
Object will be created: MyClass(Toby, Red)
Constructor is called with params:  Toby   Red
Hello, Developer
Destructor is called for Toby!

++++++++++++++++++++++++++++++++++++++++++++++++++

參考資料:Python高效開發實戰

 

【Python】-【類解析】--【指令碼執行個體】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.