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.定义类与实例化出对象

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

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

站在路飞city的角度,大家都是学生

在现实世界中:
    对象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)

 

 

 

4、如何使用类

   

(1)查看类的命名空间

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

  

运行结果
{'learning': <function LuffyStudent.learning at 0x02441738>, 
'__dict__': <attribute '__dict__' of 'LuffyStudent' objects>, 
'__weakref__': <attribute '__weakref__' of 'LuffyStudent' objects>, 
'__doc__': None,
 'eating': <function LuffyStudent.eating at 0x02441810>, 
'school': 'Luffycity', 'sleep': <function LuffyStudent.sleep at 0x024417C8>, '__module__': '__main__'} Luffycity <function LuffyStudent.eating at 0x02441810>

 

 

(2)查看类的属性

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

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

 

 

(3)增加类的属性

# 增加
LuffyStudent.addr = 'xian'
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'}


xian

 

 

(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

 

 

5.如何使用对象?

# 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)

 

  (1)__init__分析

  

  

  (2)查看stu1对象的命名空间、属性

# 查对象stu1的命名空间
print(stu1.__dict__)

# >>>
{'name': '张三', 'age': 18, 'gender': ''}

 

 

# 查对象stu1的属性
print(stu1.name)
print(stu1.gender)
print(stu1.age)

# >>>
张三
女
18

 

 

#
stu1.name = 'zhangsan'
print(stu1.__dict__)

# >>>
{'name': 'zhangsan', 'gender': '', 'age': 18}

 

 

#
stu1.addr = 'xian'
print(stu1.__dict__)

# 》》》
{'name': 'zhangsan', 'gender': '', 'addr': 'xian', 'age': 18}

 

 

# 删除
del stu1.age
print(stu1.__dict__)

# >>>
{'gender': '', 'name': 'zhangsan'}

 

  

  (3)对象stu2

stu2 = LuffyStudent('李四', '', 28)  # LuffyStudent.__init__(stu2,'李四', '男', 28)
print(stu2.__dict__)
print(stu2.name)
print(stu2.gender)
print(stu2.age)

 

# 运行结果
{'age': 28, 'gender': '', 'name': '李四'}
李四
男
28

 

 

6、属性查找

 

# 先产生类
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)调用类的技能函数

 

    def learning(self):
        print('%s is learning'%self.name)
  •   类调用
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)多个类的属性调用

    def learning(self, style):
        print('%s is learning %s'%(self.name,style))
  •   类调用
LuffyStudent.learning(stu1,'english')
LuffyStudent.learning(stu2,'chines')
LuffyStudent.learning(stu3,'math')

#>>>
张三 is learning english
李四 is learning chines
王五 is learning math
  • 对象调用
stu1.learning('english')  # LuffyStudent.learning(stu1)
stu2.learning('chinese')
stu3.learning('math')

#>>>
张三 is learning english
李四 is learning chinese
王五 is learning math

 

 

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

  • 局部变量调用
# 定义一个属性  style = ’from luffy class‘
LuffyStudent.style = 'from luffy class'

print(stu1.__dict__)
print(stu1.style)   # 调用
  • 只会到继承的父类查找,不会查找全局变量global

 

 

 

7、一切皆对象

 

 

  (1)list和LuffyStudent都是类的不同表现形式

#普通方法# 
l1 = [1,2,3]
l1.append(4)
print(l1)


# 通过类,对象,调用类的方法进行操作
l1 = list([1,2,3])
list.append(l1,4)
print(l1)

 

 

8、代码级别看面向对象

(1)在没有学习类这个概念时,数据与功能是分离的

def exc1(host,port,db,charset):
    conn=connect(host,port,db,charset)
    conn.execute(sql)
    return xxx


def exc2(host,port,db,charset,proc_name)
    conn=connect(host,port,db,charset)
    conn.call_proc(sql)
    return xxx

#每次调用都需要重复传入一堆参数
exc1('127.0.0.1',3306,'db1','utf8','select * from tb1;')
exc2('127.0.0.1',3306,'db1','utf8','存储过程的名字')

 


(2)我们能想到的解决方法是,把这些变量都定义成全局变量

HOST=‘127.0.0.1’
PORT=3306
DB=‘db1’
CHARSET=‘utf8’

def exc1(host,port,db,charset):
    conn=connect(host,port,db,charset)
    conn.execute(sql)
    return xxx


def exc2(host,port,db,charset,proc_name)
    conn=connect(host,port,db,charset)
    conn.call_proc(sql)
    return xxx

exc1(HOST,PORT,DB,CHARSET,'select * from tb1;')
exc2(HOST,PORT,DB,CHARSET,'存储过程的名字')

 

 

 

 (4)总结

  

(5)可拓展性高

  •   定义类并产生三个对象
class Chinese:
    country = 'China'

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

p1 = Chinese('alex', '', 22)
p2 = Chinese('jack', '', 32)
p3 = Chinese('tom', '', 42)

print(p1.country)
print(p2.country)
print(p3.country)

  

  • 如果我们新增一个类属性,将会立刻反映给所有对象,而对象却无需修改

  

 

 

9、小节练习

练习1:编写一个学生类,产生一堆学生对象, (5分钟)

要求:

有一个计数器(属性),统计总共实例了多少个对象
练习2:模仿王者荣耀定义两个英雄类, (10分钟)

要求:

英雄需要有昵称、攻击力、生命值等属性;
实例化出两个英雄对象;
英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡。

 

  (1)我的代码

class Student:

    count = 0
    def __init__(self):
        count += 1

stu1 = Student()
stu2 = Student()
stu3 = Student()
stu4 = Student()

print(Student.count)

   

# 练习2
class Hero:
    def __init__(self, name, attack, hp):
        self.name = name
        self.attack = attack
        self.hp = hp

    def attacked(self, anyone):
        self.hp -= anyone.attack

    def __del__(self):
        if self.hp <= 0 :
            print('%s is died'%self.name)

hero1 = Hero('akl', 35, 100)
hero2 = Hero('tom', 20, 200)
print(hero1.__dict__)
print(hero2.__dict__)

hero1.attacked(hero2)
print(hero1.__dict__)
hero2.attacked(hero1)
print(hero1.__dict__)

 

 

(2)老师代码

class Student:
    count = 0
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        Student.count += 1

    def learn(self):
        print('%s is learning'%self.name)


print(Student.__dict__)
stu1 = Student('张三', 18, '')
stu2 = Student('李四', 28, '')
stu3 = Student('王五', 38, '')
print(Student.__dict__)
print(Student.count)

 

 

# 练习2
class Akl:
    city = 'Demacia'

    def __init__(self, nickname, life_value, aggresivity):
        self.nickname = nickname
        self.life_value = life_value
        self.aggresivity = aggresivity

    def attack(self, enemy):
        enemy.life_value -= self.aggresivity


class Riven:
    city = 'Noxus'

    def __init__(self, nickname, life_value, aggresivity):
        self.nickname = nickname
        self.life_value = life_value
        self.aggresivity = aggresivity

    def attack(self, enemy):
        enemy.life_value -= self.aggresivity

akl = Akl('暗影之拳', 100, 30)
riven = Riven('锐萌萌', 100, 30)

print(riven.__dict__)
akl.attack(riven)
print(riven.life_value)
print(riven.__dict__)

 

posted @ 2018-03-13 22:46  venicid  阅读(197)  评论(0编辑  收藏  举报