【Python】-【類解析】--【腳本實例】

經過腳本事例,解析下Python中類的幾個概念在腳本中的應用python

腳本以下:函數

++++++++++++++++++++++++++++++++++++++++spa

#!/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開發

輸出結果:it

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!
class

++++++++++++++++++++++++++++++++++++++++++++++++++變量

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

相關文章
相關標籤/搜索