首页 > 代码库 > 【Python】-【类解析】--【脚本实例】

【Python】-【类解析】--【脚本实例】

通过脚本事例,解析下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】-【类解析】--【脚本实例】