1 - 面向对象基础

1、编程范式

  • 编程是 程序 员 用特定的语法+数据结构+算法 组成的代码来告诉计算机如何执行任务的过程 。
  • 两种最重要的编程范式分别是
    •   面向过程编程
    •   面向对象编程

2、面向过程编程(Procedural Programming)

  • 面向过程:核心是过程二字,过程是解决问题的步骤,设计一条流水线,机械式的思维方式
    • 优点 :复杂的问题流程化,进而简单化
    • 缺点 :可扩展性差

代码示例:

"""实现一个用户注册功能"""
# 1.用户输入
# 2.验证是否符合标准
# 3.注册


def enter():
    username = input('>:').strip()
    password = input('>:').strip()
    return {
        'username': username,
        'password': password
            }


def check(user_info):
    is_valid = True
    if len(user_info['username']) == 0:
        print('用户名不能为空')
        is_valid = False
    if len(user_info['password']) < 6:
        print('密码不能少于6个字符')
        is_valid = False
    return {
        'is_valid': is_valid,
        'user_info': user_info
    }


def register(check_info):
    if check_info['is_valid']:
        import json
        with open('users.txt', 'w', encoding='utf-8') as f:
            json.dump(check_info['user_info'], f)
        print('注册成功')


def main():
    user_info = enter()
    check_info = check(user_info)
    register(check_info)


if __name__ == '__main__':
    main()

 

如果添加一个新功能: 邮箱验证(需要动函数内部代码,这不符合开放封闭原则,因而面向过程编程可扩展性差)

 

3、面向对象编程

  • 面向对象编程:核心是 对象 ,对象是特征与技能的结合体
    • 优点:可扩展性高
    • 缺点:编程复杂度高
    • 应用场景:用户需求经常变换,互联网应用,游戏,企业内部应用。。。

4、定义类与实例化出对象

"""
类就是一系列对象相似的特征与技能的结合体
强调:站在不同的角度,得到的分类是不一样的

在现实世界中:一定先有对象,后有类
在程序中,一定先定义类,后强调类来产生对象

站在luffycity的角度,大家都是学生

在现实世界中:
    对象1:张三
        特征:
            学校='luffycity'
            名字='张三'
            性别='女'
            年龄=18
        技能:
            学习
            吃饭
            睡觉
    对象2:李四
        特征:
            学校='luffycity'
            名字='李四'
            性别='男'
            年龄=28
        技能:
            学习
            吃饭
            睡觉
    对象3:王五
        特征:
            学校='luffycity'
            名字='王五'
            性别='女'
            年龄=38
        技能:
            学习
            吃饭
            睡觉


总结现实中路飞city的学生类
    相似的特征:
        学校=’luffycity‘

    相似的技能
        学习
        吃饭
        睡觉

"""

 

代码实现如下:

# 先定义类
class LuffyStudent:
    school = 'Luffycity'  # 共有属性

    def learning(self):
        print('is learning')

    def eating(self):
        print('is eating')

    def sleep(self):
        print('is sleeping')

# 后产生对象
stu1 = LuffyStudent()
stu2 = LuffyStudent()
stu3 = LuffyStudent()
print(stu1)
print(stu2)
print(stu3)

5、如何使用类

  (1) 查看类的命名空间

# 查看类的命名空间
print(LuffyStudent.__dict__)
print(LuffyStudent.__dict__['school'])
print(LuffyStudent.__dict__['eating'])

 (2)查看类的属性

# 查  类的属性
print(LuffyStudent.school)  # LuffyStudent.__dict__['school']
print(LuffyStudent.eating)  # LuffyStudent.__dict__['eating']

# 运行结果
Luffycity
<function LuffyStudent.eating at 0x01F71738>

 (3)增加类属性

# 增加
LuffyStudent.addr = '南京'
print(LuffyStudent.__dict__)
print(LuffyStudent.addr)

# 运行结果
{'eating': <function LuffyStudent.eating at 0x005A17C8>, 
'addr': 'xian',
 '__dict__': <attribute '__dict__' of 'LuffyStudent' objects>,
 'learning': <function LuffyStudent.learning at 0x005A1738>, 
'__weakref__': <attribute '__weakref__' of 'LuffyStudent' objects>,
 'sleep': <function LuffyStudent.sleep at 0x005A1810>, 
'__doc__': None, 
'__module__': '__main__', 
'school': 'Luffycity'}


南京

 (4)删除类属性

# 删除
del LuffyStudent.addr
print(LuffyStudent.__dict__)

#>>>
{'eating': <function LuffyStudent.eating at 0x005A17C8>,
 '__dict__': <attribute '__dict__' of 'LuffyStudent' objects>,
 'learning': <function LuffyStudent.learning at 0x005A1738>, 
'__weakref__': <attribute '__weakref__' of 'LuffyStudent' objects>, 
'sleep': <function LuffyStudent.sleep at 0x005A1810>,
 '__doc__': None, '__module__': '__main__',
 'school': 'Luffycity'}

 (5)修改类属性

# 修改
LuffyStudent.school = 'OldBoy'
print(LuffyStudent.school)

#>>>
OldBoy

 

6、如何使用对象?

  • __init__ 方法用来为对象定制对象自己独有的属性
    • 如为德玛 定制自己独有属性(HP、MP)
# 1.先定义类
class LuffyStudent:
    school = 'Luffycity'

    def __init__(self, name, gender, age):
        self.name = name
        self.gender = gender
        self.age = age

    def eating(self):
        print('is eating')

    def learning(self):
        print('is learning')

# 2.后产生对象
stu1 = LuffyStudent('张三', '', 18)

7、属性查找

# 先产生类
class LuffyStudent:
    school = 'Luffy'

    def __init__(self, name, gender, age):
        self.name = name
        self.gender = gender
        self.age = age

    def learning(self):
        print('is learning')

    def eating(self):
        print('is eating')

    def sleeping(self):
        print('is sleeping')

# 后产生对象
stu1 = LuffyStudent('张三', '', 18)
stu2 = LuffyStudent('李四', '', 28)
stu3 = LuffyStudent('王五', '', 38)
print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)

# >>>
{'name': '张三', 'gender': '', 'age': 18}
{'name': '李四', 'gender': '', 'age': 28}
{'name': '王五', 'gender': '', 'age': 38}

  

  (1)类的特征属性

# 类中的数据属性:是所有对象共有的
print(LuffyStudent.school, id(LuffyStudent.school))

print(stu1.school, id(stu1.school))
print(stu2.school, id(stu2.school))
print(stu3.school, id(stu3.school))

#>>>
Luffy 43075776
Luffy 43075776
Luffy 43075776
Luffy 43075776

 (2)类的技能函数

# 类中的技能函数:是绑定给对象,绑定到不同的对象是不同的绑定方法
print(LuffyStudent.learning)
print(stu1.learning)
print(stu2.learning)
print(stu3.learning)

#>>>
<function LuffyStudent.learning at 0x02951780>
<bound method LuffyStudent.learning of <__main__.LuffyStudent object at 0x0294FA90>>
<bound method LuffyStudent.learning of <__main__.LuffyStudent object at 0x0294FAF0>>
<bound method LuffyStudent.learning of <__main__.LuffyStudent object at 0x029621F0>>

 (3)调用类的技能函数

  • 类调用
LuffyStudent.learning(stu1)
LuffyStudent.learning(stu2)
LuffyStudent.learning(stu3)

# 》》》
张三 is learning
李四 is learning
王五 is learning
  • 对象调用
stu1.learning()  # LuffyStudent.learning(stu1)
stu2.learning()
stu3.learning()

#》》》
张三 is learning
李四 is learning
王五 is learning

 (4)全局变量,局部调用

# 定义一个属性  style = ’from luffy class‘
LuffyStudent.style = 'from luffy class'

print(stu1.__dict__)
print(stu1.style)   # 调用

 

8、一切皆对象

  • 补充说明
    • 站的角度不同,定义出的类是截然不同的;
    • 现实中的类不完全等于程序中的类,比如现实中的公司类,在程序中有时需要拆分成部门类,业务类等等;
    • 有时为了编程需求,程序中也可能会定义现实中不存在的类,比如策略类,现实中并不存在,但在程序中却是一个很常出现的类
posted @ 2018-10-09 15:16  edison-chen  阅读(150)  评论(0)    收藏  举报