python(面向对象设计)

三大编程范式

1.面向过程

2.面向对象

3.函数式编程

例.对象建立,但只是单一的

# -*- coding: utf-8 -*-
people1={
    'name':'bob',
    'age':'10',
    'Gender':'man',
    'sport':'basketball'
}

people2={
    'name':'lily',
    'age':'12',
    'Gender':'men',
    'sport':'sing'
}

def do(people):
    print('%s like %s' % (people['name'],people['sport']))

def gender(people):
    print('%s is a %s' % (people['name'],people['Gender']))

do(people1)
gender(people2)

 进一步完善

# -*- coding: utf-8 -*-
def peoples(name,age,gender,sport):
    def do(people):
        print('%s like %s' % (people['name'],people['sport']))
    def sex(people):
        print('%s is a %s' % (people['name'],people['gender']))
    def init(name,age,gender,sport):
        people={
                'name':name,
                'age':age,
                'gender':gender,
                'sport':sport,
            #行为
                'do':do,
                'sex':sex,
        }
        return people
    res=init(name,age,gender,sport)

    return res

people1=peoples('bob','11','man','soccer')
people1['do'](people1)
people1['sex'](people1)

类:把一类事物的相同的特征和动作整合到一起,是一个抽象的概念。

对象:是基于类创建的一个具体的事物。是特征和动作整合到一起。

例子.创建学校类

特征:name,adder,type

动作:考试,招生,管理

简单版

# -*- coding: utf-8 -*-

def school(name,addr,type):
    def exam():
        print('------考试------')

    def enroll():
        print('------招生------')

    def administration():
        print('------管理------')
    sch={
                'name': name,
                'addr':addr,
                'type':type,
                'exam': exam,
                'enroll': enroll,
                'administration': administration
            }
    return sch
   

school1=school('实验','光明路','公立')

school1['exam']()
school1['enroll']()
school1['administration']()

 进一步加工

# -*- coding: utf-8 -*-

def school(name,addr,type):
    def exam():
        print('------考试------')

    def enroll():
        print('------招生------')

    def administration():
        print('------管理------')
    def intial(name,addr,type):
            sch={
                'name': name,
                'addr':addr,
                'type':type,
                'exam': exam,
                'enroll': enroll,
                'administration': administration
            }
            return sch
    return intial(name,addr,type)


school1=school('实验','光明路','公立')

print(school1)
school1['exam']()
school1['enroll']()
school1['administration']()

 面向对象设计:用面向对象独有的语法class去实现

 

 

 

posted on 2019-12-08 21:49  hcy12  阅读(175)  评论(0编辑  收藏  举报

导航