python基础教程笔记-项目1-即时标记-Day3

昨天实现了简单的txt转html,今天更深入一步。

主要了解下带星号的参数、getattr函数和callable函数

先看Handler类:

class Handler:
    def callback(self, prefix, name, *args):
        method = getattr(self, prefix+name, None)
        if callable(method): return method(*args)
    def start(self, name):
        self.callback('start_', name)
    def end(self, name):
        self.callback('end_', name)
    def sub(self, name):
        def substitution(match):
            result = self.callback('sub_', name, match)
            if result is None: match.group(0)
            return result
        return substitution
def sub_test(self, name):
        print name

今天了解下callback函数

先看callback的参数

带*的参数是什么意思?

下面来看一段代码:

def calc(*numbers):
	sum = 0
	for i in numbers:
		sum = sum + i
	return sum
	
result = calc(1,2,3)
temp = calc()
print result
printa temp

执行结果为:

也就是说,带*的参数代表一个数量可变的参数(长度可为0)。其具体讲解见链接:

http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001374738449338c8a122a7f2e047899fc162f4a7205ea3000

然后是getattr

其中官方文档对getattr()的解释为:
getattr(object, name[, default]) 

Return the value of the namedattribute of object. name must be a string. If the string is the name of one ofthe object's attributes, the result is the value of that attribute. Forexample, getattr(x, 'foobar') is equivalent to x.foobar. If the named attributedoes not exist, default is returned if provided, otherwise AttributeError israised.

也就是说,若对象中有名为name(name必须是一个字符串)的属性,则返回该属性。如果对象中没有该属性,若getattr中提供了default参数,返回提供的default,否则抛出一个AttributeError错误。

看下面这个例子:

lass Test:
	def print_hello(self):
		print 'func print_hello work'
		
a = Test()
b = getattr(a,'print_hello',None)
print b
b()
b = getattr(a,'NoFunc',None)
print b

执行结果为:



第一次使用getattr函数时,b尝试获取a中的print_hello函数,从打印结果可看出获取成功之后我们调用了b。

第二次使用getattr函数时,b尝试获取a中的NoFunc函数,从打印结果可看出a中并没有名为NoneFunc的函数,因此b的值为None

接着看下callable函数

看图


很明显,若callable中的参数为函数名,则返回True,否则返回False。另外可以看到命令行中func()执行了一次。函数的执行发生在a = func()这一过程中

综上,函数callback(self,prefix, name, *args)的功能为:

在使用callback函数的对象中查询其是否拥有名为’prefix+name’的函数。若有该函数,则调用该函数,并返回该函数的执行结果。(函数名为prefix+name,参数为*args)。下面用代码试下:

class CalTest:
	def callback(self,prefix,name,*args):
		method = getattr(self,prefix+name,None)
		if callable(method):return method(*args)
	def printSum(self,*arg):
		sum = 0
		for i in arg:
			sum = sum + i
		return sum
		
a = CalTest();
b = a.callback('print','Sum',1,2,3)
print b
b = a.callback('print','Sum')
print b
执行结果为:



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值