《Python高效开发实战》读书笔记(2)

面向对象编程

一. 例子一:构造函数,析构函数,类成员变量,实例成员变量

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class MyClass(object):  
    #这里的message是类成员变量,也就是MyClass类和所有MyClass对象共享该成员变量
    message = 'Hello, Developer'
    
    def show(self):
        print self.message
        print "Here is %s in %s!" %(self.name, self.color)
    
    #构造函数
    def __init__(self, name="unset", color='black'):
        print "Constructor is called with params: ",name," ",color
        #这里的self.name和self.color是实例成员变量
        self.name = name
        self.color = color
    
    #析构函数
    def __del__(self):
        print "Destructor is called for %s!" %self.name
        
    


if __name__ == "__main__":
    inst2 = MyClass("David")
    inst2.show()

    print "Color of inst2 is ",inst2.color, "\n"

    inst3 = MyClass('Lisa','yellow')
    inst3.show()
    print "Name of inst3 is ",inst3.name,"\n"

    #析构函数,可以显式调用。否则,程序会自动调用
    del inst2, inst3

运行结果

Constructor is called with params:  David   black
Hello, Developer
Here is David in black!
Color of inst2 is  black 

Constructor is called with params:  Lisa   yellow
Hello, Developer
Here is Lisa in yellow!
Name of inst3 is  Lisa 

Destructor is called for David!
Destructor is called for Lisa!

二. 静态函数和类函数

到目前为止,绝大多数的“类成员变量”,均与实例绑定,即只能通过对象访问,而不可以通过类名访问。

 

而事实上,Python中,支持两种基于类名访问成员的函数:“静态函数”和“类函数”

不同点在于,类函数有一个隐形参数cls用来获取类信息,而静态函数没有该参数。

 

静态函数使用装饰器@staticmethod定义

类函数使用装饰器@classmethod定义

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class MyClass(object):
    
    message = 'hello,Developer'
    
    def show(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 "Destrcutor is called %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
Destrcutor is called Toby! 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值