每天学一点,形成一种知识复利问题
问题31:静态函数和类函数
分析:静态函数使用装饰器@staticmethod定义,类函数使用装饰器@classmethod定义
demoCode:
#! /usr/bin/python3
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 "Destructor is called for %s!" % self.name
MyClass.printMessage()
inst = MyClass.createObj("Toby", "Red")
print inst.message
del inst
问题32:回调函数
分析:回调函数就是一个通过函数指针调用的函数
import os,sys
Find={
'Type':'',
'Color':'',
'Size':''
}#定义汇报内容
def CallFun(cmd,Find):#回调函数的定义,在这里处理各种回调情况
if cmd=='Type':
if Find['Type']=='Dog' or Find['Type']=='Cat':
print 'A Pet:'
else:
print 'A Transport:'
elif cmd=='Print':
print Find
else:
print 'error'
def GiveInfo(i):
type0=['Dog','Cat']
type1=['Car','Truck']
color0=['Black','White','Pink']
size0=['Big','Middle','Small']
t0=i % 2
if t0== 0:
Find['Type'] = type0[i%2]
else:
Find['Type'] = type1[i%2]
Find['Color'] = color0[i%3]
Find['Size'] = size0[i%3]
def FindObj(num,cmd,CallBackFun):#发现目标,启动回调函数
GiveInfo(num)#门卫填报信息
CallBackFun(cmd,Find)#启动回调函数
if __name__ == '__main__':
cmds=['Type','Print','Try']
for i in range(0,10):#定义十次上报
print '----------%d-------------'%i
FindObj(i,cmds[i%3],CallFun)#这里注册回调函数