24类和对象---使用字典实现
1、不要简单的认为面向对象就是使用class A ,面向对象是一种编程思想,用函数也可以面向对象编程。
面向过程、面向对象、函数式编程只是不同的编程范式,本身没有好坏之分,看用的人了。Linux的内核就是用C语言写成的,能说差吗?
2、用函数进行面向对象编程例子
类就是一些函数的包,只是类支持继承,我们也可以把函数存储到字典中,但是没有必要,使用类是很自然的事情
dog1 = { 'name':'aa', 'gender':'公', 'type':'藏獒', } dog2 = { 'name':'cc', 'gender':'公', 'type':'藏獒', } person1 = { 'name':'mm', 'gender':'女', 'type':'人', } def run(dog): print('the {} run....'.format(dog['name'])) def eat(dog): print('the {} eat....'.format(dog['name'])) eat(dog1) eat(dog2) eat(person1) #----------把函数也封闭到字典里-------------------- def dog(): def run(dog): print('the {} run....'.format(dog['name'])) def eat(dog): print('the {} eat....'.format(dog['name'])) # 把函数也封装在字典里,但这时候又写死了 dog1 = { 'name':'aa', 'gender':'公', 'type':'藏獒', 'run':run, 'eat':eat, } return dog1 d1 = dog() d1['run'](d1) # ------------------------------------------------------ def dog(name,gender,type): def run(dog): print('the {} run....'.format(dog['name'])) def eat(dog): print('the {} eat....'.format(dog['name'])) dog1 = { 'name':name, 'gender':gender, 'type':type, 'run':run, 'eat':eat, } return dog1 #----------------定义init()用来初始化----------------------- def dog(name,gender,type): def run(dog): print('the {} run....'.format(dog['name'])) def eat(dog): print('the {} eat....'.format(dog['name'])) def init(name,gender,type): dog1 = { 'name':name, 'gender':gender, 'type':type, 'run':run, 'eat':eat, } return dog1 return init(name, gender, type) d1 = dog('aa','公','藏獒') d1['run'](d1) d2 = dog('bb','公','藏獒') d2['run'](d2)