24类和对象---使用字典实现

参考Python开发之路

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)

 

posted @ 2021-04-05 14:24  cheng4632  阅读(69)  评论(0编辑  收藏  举报