码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-12-28 12:26:07      阅读:208      评论:0      收藏:0      [点我收藏+]

标签: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】-【类解析】--【脚本实例】

标签:style   icm   ted   --   cal   turn   构造   替代   env   

原文地址:http://www.cnblogs.com/cuisi/p/6228555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!