#人狗大战,定义了两个函数,一个person,一个dog,函数体内定义的是属性,内部函数定义为‘攻击’,创建对象后调用此函数可以进行改变血量,即受到攻击。
def person(name,hp,ack,sex): person = { '名字':name, '血量':hp, '攻击力':ack, '性别':sex, } def skill(dog): dog['血量'] -= person['攻击力'] if dog['血量'] > 0: return '狗%s被%s打了,剩余%s血量'%(dog['名字'],person['名字'],dog['血量']) else: return '哦豁,狗%s被你打死了'%(dog['名字']) person['skill_1'] = skill #调用person后,执行到这里,在person字典中添加到了键值对“skill_1”:skill,skill指向的是skill函数的内存地址 return person #将含有key为skill_1,value为skill的内存地址的字典返回 def dog(name,hp,ack,sex): dog = { '名字':name, '血量':hp, '攻击力':ack, '性别':sex, } def skill(person): person['血量'] -= dog['攻击力'] return '%s被一条叫%s的狗咬了了,剩余%s血量'%(person['名字'],dog['名字'],person['血量']) dog['dog_skill'] = skill return dog aike = person('aike',1000,100,'男') #接收到了返回来的字典,并且字典里含有key为skill_1,value为skill内存地址 chen = dog('chenfan',200,20,'huntaway') print(aike) print(chen) print(aike['skill_1'](chen))#获取字典key为skill_1的值,执行的是skill函数,并且把对象chen(字典)传了进去,函数内就能够调用到字典chen内的元素 print(aike['skill_1'](chen)) print(aike['skill_1'](chen)) print(chen['dog_skill'](aike))
知识点:闭包,即外部函数的变量被内部函数调用
思考:当函数返回值为可变数据类型(字典)时,可在返回之前添加一个键值对,赋值可以是当前作用域函数的内存地址,这样就能以字典获取vaule的形式调用到内部函数(赋值的内存地址指向的函数)
转换为面向对象方式编写:
class Person: def __init__(self,name,hp,ack,sex): self.name = name self.hp = hp self.ack = ack self.sex = sex def skill(self,dog): chenfan.hp -= aike.ack return '这条叫%s的狗,被%s打了,还有%s血'%(dog.name,aike.name,dog.hp) class Dog: def __init__(self,name,hp,ack,sex): self.name = name self.hp = hp self.ack = ack self.sex = sex def skill(self,person): aike.hp -= chenfan.ack return '%s被一条名叫%s的狗咬了,还剩%s血'%(person.name,chenfan.name,person.hp) aike = Person('aike',1000,100,'男') chenfan = Dog('chenfan',200,20,'teddy') print(aike.skill(chenfan)) print(chenfan.skill(aike))