python面向对象重新梳理
关于本篇博文:
面向对象中所有的内容的重新梳理,其实面向对象的知识早在一个多月前就学习过并整理过,但是发现还是有所欠缺,故在此以极其简介的语言风格重新梳理一遍
面向对象详细介绍:http://www.cnblogs.com/wyb666/p/8728621.html
参考文章:http://www.cnblogs.com/linhaifeng/articles/6182264.html
一、面向过程与面向对象
1.面向过程
- # 面向过程:核心是过程二字,过程指的是解决问题的步骤,设计一条流水线,机械式的思维方式
- # 优点:复杂的问题流程化,进而简单化
- # 缺点:可扩展性差
- # 以下是面向过程的实例(用户注册),用户注册的流程为:用户输入信息->判断用户信息是否合法->合法就保存用户数据
- import json
- import re
- def interactive():
- """
- 用户输入信息
- :return: 以字典形式返回注册账号的信息
- """
- name = input('name>>>').strip()
- pwd = input('password>>>').strip()
- email = input('email>>> ').strip()
- return {
- 'name': name,
- 'pwd': pwd,
- 'email': email
- }
- def check(user_info):
- """
- 判断用户输入信息是否正确
- :param user_info: 用户信息
- :return: 返回字典(用户信息及合法性)
- """
- is_valid = True # is_valid表示合法性
- # 判断用户名的合法性
- if len(user_info['name']) == 0:
- print('用户名不能为空')
- is_valid = False
- # 判断密码的合法性
- if len(user_info['pwd']) < 6:
- print('密码不能少于6位')
- is_valid = False
- # 判断邮箱格式的合法性
- if not re.search(r'@.*?\.com$', user_info['email']):
- print('邮箱格式不合法')
- is_valid = False
- return {
- 'is_valid': is_valid,
- 'user_info': user_info
- }
- def register(check_info):
- """
- 如果合法就注册用户(把用户信息导入json文件中)
- :param check_info: 包含用户信息及合法性的字典
- :return:
- """
- if check_info['is_valid']:
- with open('db.json', 'w', encoding='utf-8') as f:
- json.dump(check_info['user_info'], f)
- # 程序主函数
- def main():
- user_info = interactive()
- check_info = check(user_info)
- register(check_info)
- # 程序主入口
- if __name__ == '__main__':
- main()
2.面向对象
- # 面向对象:核心就是对象二字,对象就是特征与技能的结合体
- # 优点:可扩展性强
- # 缺点:编程复杂度高
- # 应用场景:用户需求经常变化,互联网应用,游戏,企业内部应用
- # 类就是一系列对象相似的特征与技能的结合体 强调:站在不同的角度,得到的分类是不一样的
- # 另外在现实世界中一定先有对象,后有类; 在程序中一定得先定义类,后调用类来产生对象
- # 先定义类
- class Student:
- # 特征:
- school = 'luffycity'
- # 技能:
- def learn(self):
- print('is learning')
- def eat(self):
- print('is sleeping')
- # 后产生对象
- stu1 = Student()
- stu2 = Student()
- stu3 = Student()
- print(stu1)
- print(stu2)
- print(stu3)
二、面向对象入门
1.类与对象的基本使用
(1)类的定义
- # 定义类
- class Student:
- # 数据属性
- school = 'luffycity'
- # 函数属性
- def learn(self):
- print('is learning')
- def eat(self):
- print('is sleeping')
- # 查看类的名称空间
- print(Student.__dict__)
- print(Student.__dict__['school'])
- print(Student.__dict__['learn'])
- print(Student.__dict__['eat'])
- # 查
- print(Student.school) # Student.__dict__['school']
- print(Student.learn) # Student.__dict__['learn']
- print(Student.eat) # Student.__dict__['eat']
- # 增
- Student.county = 'China'
- print(Student.__dict__)
- print(Student.county)
- # 删
- del Student.county
- # 改
- Student.school = 'oldboy'
- #python为类内置的特殊属性
- 类名.__name__# 类的名字(字符串)
- 类名.__doc__# 类的文档字符串
- 类名.__base__# 类的第一个父类(在讲继承时会讲)
- 类名.__bases__# 类所有父类构成的元组(在讲继承时会讲)
- 类名.__dict__# 类的字典属性
- 类名.__module__# 类定义所在的模块
- 类名.__class__# 实例对应的类(仅新式类中)
类内置的特殊属性
(2)__init__方法(构造函数)及对象的定义
- # __init__方法用来为对象定制对象自己独有的特征
- class Student:
- school = 'luffycity'
- # 构造函数
- def __init__(self, name, sex, age):
- self.Name = name
- self.Sex = sex
- self.Age = age
- def learn(self):
- print('is learning')
- def eat(self):
- print('is sleeping')
- # 定义对象
- stu1 = Student('王二丫', '女', 18) # Student.__init__(stu1,'王二丫','女',18)
- # __init__方法后实例化的步骤:
- # 1、先产生一个空对象stu1
- # 2、Student.__init__(stu1,'王二丫','女',18)
- # 对象的操作:
- # 查
- print(stu1.__dict__)
- # 改
- stu1.Name = '李二丫'
- print(stu1.__dict__)
- # 删除
- del stu1.Name
- print(stu1.__dict__)
- # 增
- stu1.class_name = 'python开发'
- print(stu1.__dict__)
2.属性查找与绑定方法
关于绑定方法详细解释:https://www.cnblogs.com/vipchenwei/p/7126772.html
类有两种属性:数据属性和函数属性
- 类的数据属性是所有对象共享的
- 类的函数属性是绑定给对象用的
- class Student:
- school = 'luffycity'
- def __init__(self, name, sex, age):
- self.Name = name
- self.Sex = sex
- self.Age = age
- def learn(self):
- print('%s is learning' % self.Name)
- def eat(self, food):
- print('%s is eating' % self.Name)
- print("food:", food)
- stu1 = Student('王二丫', '女', 18)
- stu2 = Student('李三炮', '男', 38)
- stu3 = Student('张铁蛋', '男', 48)
- # 对象:特征与技能的结合体
- # 类:类是一系列对象相似的特征与相似的技能的结合体
- # 类中的数据属性是所有对象共有的
- print(Student.school, id(Student.school))
- print(stu1.school, id(stu1.school))
- print(stu2.school, id(stu2.school))
- print(stu3.school, id(stu3.school))
- # 类中的函数属性:是绑定给对象使用的,绑定到不同的对象是不同的绑定方法,对象调用绑定方式时,会把对象本身当作第一个传入,传给self
- print(Student.learn)
- stu1.learn() # 调用对象的learn方法
- stu2.learn()
- stu3.learn()
- print(stu1.eat)
- stu1.eat("包子") # eat(stu1, "包子")
- print(stu2.eat)
- print(stu3.eat)
3.python中一切都是对象
- # python一切皆对象,在python3里统一类类与类型的概念
- class Student:
- school = 'luffycity'
- def __init__(self, name, sex, age):
- self.Name = name
- self.Sex = sex
- self.Age = age
- # stu1.Name='王二丫'
- # stu1.Sex='女'
- # stu1.Age=18
- def learn(self, x):
- print('%s is learning %s' % (self.Name, x))
- def eat(self):
- print('%s is sleeping' % self.Name)
- # 以下均是对象:
- print(type([1, 2]))
- print(list)
- print(Student)
- l1 = [1, 2, 3] # l=list([1,2,3]) 本质上是实例化对象
- l2 = [] # l=list([1,2,3]) 本质上实例化对象
- l1.append(4) # list.append(l1,4) 本质上是调用对象的绑定方法
- list.append(l1, 4) # 和上一句同理
- print(l1)
4.面向对象可拓展性与练习
(1)面向对象可拓展性实例:
- # 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 = 'db'
- 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, '存储过程的名字')
- # 3、但是2的解决方法也是有问题的,按照2的思路,我们将会定义一大堆全局变量,这些全局变量并没有做任何区分,即能够被所有功能使用,
- # 然而事实上只有HOST,PORT,DB,CHARSET是给exc1和exc2这两个功能用的。言外之意:我们必须找出一种能够将数据与操作数据的方法组合
- # 到一起的解决方法,这就是我们说的类了
- class MySQLHandler:
- def __init__(self, host, port, db, charset='utf8'):
- self.host = host
- self.port = port
- self.db = db
- self.charset = charset
- def exc1(self, sql):
- conn = connect(self.host, self.port, self.db, self.charset)
- res = conn.execute(sql)
- return res
- def exc2(self, sql):
- conn = connect(self.host, self.port, self.db, self.charset)
- res = conn.call_proc(sql)
- return res
- obj = MySQLHandler('127.0.0.1', 3306, 'db1')
- obj.exc1('select * from tb1;')
- obj.exc2('存储过程的名字')
- # 改进
- class MySQLHandler:
- def __init__(self, host, port, db, charset='utf8'):
- self.host = host
- self.port = port
- self.db = db
- self.charset = charset
- self.conn = connect(self.host, self.port, self.db, self.charset)
- def exc1(self, sql):
- return self.conn.execute(sql)
- def exc2(self, sql):
- return self.conn.call_proc(sql)
- obj = MySQLHandler('127.0.0.1', 3306, 'db1')
- obj.exc1('select * from tb1;')
- obj.exc2('存储过程的名字')
(2)练习1
- # 练习1:编写一个学生类,产生一堆学生对象
- # 要求: 有一个计数器(属性),统计总共实例了多少个对象
- class Student:
- school = 'luffycity'
- count = 0
- def __init__(self, name, age, sex):
- self.name = name
- self.age = age
- self.sex = sex
- Student.count += 1 # 等价于self.count+=1
- def learn(self):
- print('%s is learing' % self.name)
- stu1 = Student('alex', 'male', 38)
- stu2 = Student('jinxing', 'female', 78)
- stu3 = Student('egon', 'male', 18)
- print(Student.count)
- print(stu1.count)
- print(stu2.count)
- print(stu3.count)
- print(stu1.__dict__)
- print(stu2.__dict__)
- print(stu3.__dict__)
(3)练习2
- # 练习2:模仿LoL定义两个英雄类
- # 要求:
- # 英雄需要有昵称、攻击力、生命值等属性;
- # 实例化出两个英雄对象;
- # 英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡。
- class Garen:
- camp = '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:
- camp = '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
- # 用类实例化对象
- g1 = Garen('草丛伦', 100, 30)
- r1 = Riven('可爱的锐雯雯', 80, 50)
- print(r1.life_value)
- g1.attack(r1)
- print(r1.life_value)
(4)补充
- (1)站的角度不同,定义出的类是截然不同的,详见面向对象实战之需求分析
- (2)现实中的类并不完全等于程序中的类,比如现实中的公司类,在程序中有时需要拆分成部门类,业务类......
- (3)有时为了编程需求,程序中也可能会定义现实中不存在的类,比如策略类,现实中并不存在,但是在程序中却是一个很常见的类
三、面向对象进阶
1.继承
- # 单继承与多继承:
- class ParentClass1: #定义父类
- pass
- class ParentClass2: #定义父类
- pass
- class SubClass1(ParentClass1): #单继承,基类是ParentClass1,派生类是SubClass
- pass
- class SubClass2(ParentClass1,ParentClass2): # 多继承,用逗号分隔开多个继承的类
- pass
- # 经典类与新式类:
- 只在python2中才分新式类和经典类,python3中统一都是新式类
- 在python2中,没有显式的继承object类的类,以及该类的子类,都是经典类
- 在python2中,显式地声明继承object的类,以及该类的子类,都是新式类
- 在python3中,无论是否继承object,都默认继承object,即python3中所有类均为新式类
- 提示:如果没有指定基类,python的类会默认继承object类,object是所有python类的基类,它提供了一些常见方法(如__str__)的实现
- # 上面练习2可以用继承重写:
- class Hero:
- x=3
- 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 Garen(Hero):
- pass
- class Riven(Hero):
- pass
- g1=Garen('刚们',29,30)
- print(g1.nickname,g1.life_value,g1.aggresivity)
- g1.x=1
- print(g1.x)
- # 属性查找小练习:
- # 一切属性查找均从对象开始查找,找不到就向上找父类
- class Foo:
- def f1(self):
- print('from Foo.f1')
- def f2(self):
- print('from Foo.f2')
- self.f1() #b.f1()
- class Bar(Foo):
- def f1(self):
- print('from Bar.f1')
- b=Bar()
- # print(b.__dict__)
- b.f2()
2.派生
子类也可以添加自己新的属性或者在自己这里重新定义这些属性(不会影响到父类),需要注意的是,一旦重新定义了自己的属性且与父类重名,那么调用新增的属性时,就以自己为准
在子类中,新建的重名的函数属性,在编辑函数内功能的时候,有可能需要重用父类中重名的那个函数功能,应该是用调用普通函数的方式,即:类名.func(),此时就与调用普通函数无异了,因此即便是self参数也要为其传值
- class Hero:
- 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 Garen(Hero):
- camp = 'Demacia'
- def attack(self, enemy):
- print('from Garen Class')
- class Riven(Hero):
- camp = 'Noxus'
- def __init__(self, nickname, aggressivity, life_value, skin):
- Hero.__init__(self, nickname, aggressivity, life_value) # 调用父类功能
- self.skin = skin # 新属性
- def attack(self, enemy): # 在自己这里定义新的attack,不再使用父类的attack,且不会影响父类
- Hero.attack(self, enemy) # 调用功能
- print('from riven')
- def fly(self): # 在自己这里定义新的
- print('%s is flying' % self.nickname)
- g = Garen('草丛伦', 100, 30)
- r = Riven('锐雯雯', 80, 50, '比基尼')
- # print(g.camp)
- # g.attack(r)
- # print(r.life_value)
- g.attack(r)
3.新式类和旧式类
当类为新式类时,多继承下属性查找的方式为深度优先;当类为旧式类时,多继承下属性查找的方式为广度优先
- # 新式类与经典类:
- # 在python2中-》经典类:没有继承object的类,以及它的子类都称之为经典类
- #
- # class Foo:
- # pass
- #
- # class Bar(Foo):
- # pass
- #
- #
- # 在python2中-》新式类:继承object的类,以及它的子类都称之为新式类
- # class Foo(object):
- # pass
- #
- # class Bar(Foo):
- # pass
- # 在python3中-》新式类:一个类没有继承object类,默认就继承object
- # class Foo():
- # pass
- # print(Foo.__bases__)
多继承的测试代码:
- # 验证多继承情况下的属性查找:
- class A:
- # def test(self):
- # print('from A')
- pass
- class B(A):
- # def test(self):
- # print('from B')
- pass
- class C(A):
- # def test(self):
- # print('from C')
- pass
- class D(B):
- # def test(self):
- # print('from D')
- pass
- class E(C):
- # def test(self):
- # print('from E')
- pass
- class F(D, E):
- # def test(self):
- # print('from F')
- pass
- # F,D,B,E,C,A
- print(F.mro())
- f = F()
- f.test()
多继承测试
4.在子类中重用父类的属性
(1)指名道姓(不依赖继承)
- class Hero:
- 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 Garen(Hero):
- camp='Demacia'
- def __init__(self,nickname,life_value,aggresivity,weapon):
- # self.nickname=nickname
- # self.life_value=life_value
- # self.aggresivity=aggresivity
- Hero.__init__(self,nickname,life_value,aggresivity)
- self.weapon=weapon
- def attack(self,enemy):
- Hero.attack(self,enemy) # 指名道姓
- print('from Garen Class')
- g=Garen('草丛伦',100,30,'金箍棒')
- print(g.__dict__)
(2)super() (依赖继承)
- class Hero:
- 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 Garen(Hero):
- camp='Demacia'
- def __init__(self,nickname,life_value,aggresivity,weapon):
- # self.nickname=nickname
- # self.life_value=life_value
- # self.aggresivity=aggresivity
- # super(Garen,self).__init__(nickname,life_value,aggresivity)
- super().__init__(nickname,life_value,aggresivity)
- self.weapon=weapon
- def attack(self,enemy):
- Hero.attack(self,enemy) # 指名道姓
- print('from Garen Class')
- g=Garen('草丛伦',100,30,'金箍棒')
- print(g.__dict__)
(3)思考
- class A:
- def f1(self):
- print('from A')
- super().f1()
- class B:
- def f1(self):
- print('from B')
- class C(A, B):
- pass
- print(C.mro())
- # [<class '__main__.C'>,
- # <class '__main__.A'>,
- # <class '__main__.B'>,
- # <class 'object'>]
- c = C()
- c.f1()
上述代码输出结果为:
- [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
- from A
- from B
5.组合
组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合
- class People:
- school = 'luffycity'
- def __init__(self, name, age, sex):
- self.name = name
- self.age = age
- self.sex = sex
- class Teacher(People):
- def __init__(self, name, age, sex, level, salary, ):
- super().__init__(name, age, sex)
- self.level = level
- self.salary = salary
- def teach(self):
- print('%s is teaching' % self.name)
- class Student(People):
- def __init__(self, name, age, sex, class_time, ):
- super().__init__(name, age, sex)
- self.class_time = class_time
- def learn(self):
- print('%s is learning' % self.name)
- class Course:
- def __init__(self, course_name, course_price, course_period):
- self.course_name = course_name
- self.course_price = course_price
- self.course_period = course_period
- def tell_info(self):
- print('课程名<%s> 课程价钱<%s> 课程周期<%s>' % (self.course_name, self.course_price, self.course_period))
- class Date:
- def __init__(self, year, mon, day):
- self.year = year
- self.mon = mon
- self.day = day
- def tell_info(self):
- print('%s-%s-%s' % (self.year, self.mon, self.day))
- # 实例化对象
- teacher1 = Teacher('alex', 18, 'male', 10, 3000, )
- teacher2 = Teacher('egon', 28, 'male', 30, 3000, )
- python = Course('python', 3000, '3mons')
- linux = Course('linux', 2000, '4mons')
- # 组合实例:
- # 设置教师课程
- teacher1.course = python
- teacher2.course = python
- print(teacher1.course)
- print(teacher2.course)
- print(teacher1.course.course_name)
- print(teacher2.course.course_name)
- teacher1.course.tell_info()
- # 实例化学生对象并设置学生课程
- student1 = Student('张三', 28, 'female', '08:30:00')
- student1.course1 = python
- student1.course2 = linux
- student1.course1.tell_info()
- student1.course2.tell_info()
- student1.courses = []
- student1.courses.append(python)
- student1.courses.append(linux)
- # 实例化学生对象并设置学生生日及学生课程
- student1 = Student('张三', 28, 'female', '08:30:00')
- d = Date(1988, 4, 20)
- python = Course('python', 3000, '3mons')
- student1.birh = d
- student1.birh.tell_info()
- student1.course = python
- student1.course.tell_info()
6.接口及多态
(1)接口
- # IAnimal .java Java 语言中的接口很好的展现了接口的含义
- /*
- * Java的Interface接口的特征:
- * 1)是一组功能的集合,而不是一个功能
- * 2)接口的功能用于交互,所有的功能都是public,即别的对象可操作
- * 3)接口只定义函数,但不涉及函数实现
- * 4)这些功能是相关的,都是动物相关的功能,但光合作用就不适宜放到IAnimal里面了 */
- package com.oo.demo;
- public interface IAnimal {
- public void eat();
- public void run();
- public void sleep();
- public void speak();
- }
- # Pig.java:猪”的类设计,实现了IAnnimal接口
- package com.oo.demo;
- public class Pig implements IAnimal{ //如下每个函数都需要详细实现
- public void eat(){
- System.out.println("Pig like to eat grass");
- }
- public void run(){
- System.out.println("Pig run: front legs, back legs");
- }
- public void sleep(){
- System.out.println("Pig sleep 16 hours every day");
- }
- public void speak(){
- System.out.println("Pig can not speak"); }
- }
- # Person2.java
- /*
- *实现了IAnimal的“人”,有几点说明一下:
- * 1)同样都实现了IAnimal的接口,但“人”和“猪”的实现不一样,为了避免太多代码导致影响阅读,这里的代码简化成一行,但输出的内容不一样,实际项目中同一接口的同一功能点,不同的类实现完全不一样
- * 2)这里同样是“人”这个类,但和前面介绍类时给的类“Person”完全不一样,这是因为同样的逻辑概念,在不同的应用场景下,具备的属性和功能是完全不一样的 */
- package com.oo.demo;
- public class Person2 implements IAnimal {
- public void eat(){
- System.out.println("Person like to eat meat");
- }
- public void run(){
- System.out.println("Person run: left leg, right leg");
- }
- public void sleep(){
- System.out.println("Person sleep 8 hours every dat");
- }
- public void speak(){
- System.out.println("Hellow world, I am a person");
- }
- }
- # Tester03.java
- package com.oo.demo;
- public class Tester03 {
- public static void main(String[] args) {
- System.out.println("===This is a person===");
- IAnimal person = new Person2();
- person.eat();
- person.run();
- person.sleep();
- person.speak();
- System.out.println("\n===This is a pig===");
- IAnimal pig = new Pig();
- pig.eat();
- pig.run();
- pig.sleep();
- pig.speak();
- }
- }
java中的接口(Interface)
注:hi boy,给我开个查询接口。。。此时的接口指的是:自己提供给使用者来调用自己功能的方式\方法\入口
接口提取了一群类共同的函数,可以把接口当做一个函数的集合,然后让子类去实现接口中的函数
这么做的意义在于归一化,什么叫归一化,就是只要是基于同一个接口实现的类,那么所有的这些类产生的对象在使用时,从用法上来说都一样
归一化的好处在于:
- 让使用者无需关心对象的类是什么,只需要的知道这些对象都具备某些功能就可以了,这极大地降低了使用者的使用难度。
- 使得高层的外部使用者可以不加区分的处理所有接口兼容的对象集合
- 就象linux的泛文件概念一样,所有东西都可以当文件处理,不必关心它是内存、磁盘、网络还是屏幕
模仿interface:在python中根本就没有一个叫做interface的关键字,如果非要去模仿接口的概念
可以借助第三方模块:http://pypi.python.org/pypi/zope.interface
twisted的twisted\internet\interface.py里使用zope.interface
文档https://zopeinterface.readthedocs.io/en/latest/
设计模式:https://github.com/faif/python-patterns
也可以使用继承来实现:
- 继承基类的方法,并且做出自己的改变或者扩展(代码重用):实践中,继承的这种用途意义并不很大,甚至常常是有害的。因为它使得子类与基类出现强耦合。
- 声明某个子类兼容于某基类,定义一个接口类(模仿java的Interface),接口类中定义了一些接口名(就是函数名)且并未实现接口的功能,子类继承接口类,并且实现接口中的功能
注子类完全可以不用去实现接口 ,这就用到了抽象类
(2)抽象类
与java一样,python也有抽象类的概念但是同样需要借助模块实现,抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化
为什么要有抽象类:
- 如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类就是从一堆类中抽取相同的内容而来的,内容包括数据属性和函数属性
- 比如我们有香蕉的类,有苹果的类,有桃子的类,从这些类抽取相同的内容就是水果这个抽象的类,你吃水果时,要么是吃一个具体的香蕉,要么是吃一个具体的桃子。。。。。。你永远无法吃到一个叫做水果的东西
- 从设计角度去看,如果类是从现实对象抽象而来的,那么抽象类就是基于类抽象而来的
- 从实现角度来看,抽象类与普通类的不同之处在于:抽象类中只能有抽象方法(没有实现功能),该类不能被实例化,只能被继承,且子类必须实现抽象方法
抽象类与接口:
- 抽象类的本质还是类,指的是一组类的相似性,包括数据属性(如all_type)和函数属性(如read、write),而接口只强调函数属性的相似性
- 抽象类是一个介于类和接口直接的一个概念,同时具备类和接口的部分特性,可以用来实现归一化设计
- import abc
- # 抽象类的标准写法:
- class Animal(metaclass=abc.ABCMeta): # 只能被继承,不能被实例化
- all_type = 'animal'
- @abc.abstractmethod # 被装饰的方法必须被子类重写
- def run(self):
- pass
- @abc.abstractmethod
- def eat(self):
- pass
- # animal=Animal() -》 该代码无法运行会报错
- class People(Animal):
- def run(self):
- print('people is running')
- def eat(self):
- print('people is eating')
- class Pig(Animal):
- def run(self):
- print('people is walking')
- def eat(self):
- print('people is eating')
- class Dog(Animal):
- def run(self):
- print('people is walking')
- def eat(self):
- print('people is eating')
- peo1 = People()
- pig1 = Pig()
- dog1 = Dog()
- peo1.eat()
- pig1.eat()
- dog1.eat()
- print(peo1.all_type)
(3)多态与多态性
多态详细解释: http://www.cnblogs.com/linhaifeng/articles/7340687.html
- # 多态:同一类事物的多种形态
- import abc
- class Animal(metaclass=abc.ABCMeta): # 同一类事物:动物
- @abc.abstractmethod
- def talk(self):
- pass
- class People(Animal): # 动物的形态之一:人
- def talk(self):
- print('say hello')
- class Dog(Animal): # 动物的形态之二:狗
- def talk(self):
- print('say wangwang')
- class Pig(Animal): # 动物的形态之三:猪
- def talk(self):
- print('say aoao')
- class Cat(Animal):
- def talk(self):
- print('say miamiao')
- # 多态性:指的是可以在不考虑对象的类型的情况下而直接使用对象
- peo1 = People()
- dog1 = Dog()
- pig1 = Pig()
- cat1 = Cat()
- peo1.talk()
- dog1.talk()
- pig1.talk()
- def func(animal):
- animal.talk()
- func(peo1)
- func(pig1)
- func(dog1)
- func(cat1)
(4)鸭子类型
逗比时刻:
Python崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子
python程序员通常根据这种行为来编写程序。例如,如果想编写现有对象的自定义版本,可以继承该对象,也可以创建一个外观和行为像,但与它无任何关系的全新对象,后者通常用于保存程序组件的松耦合度。
例1:利用标准库中定义的各种‘与文件类似’的对象,尽管这些对象的工作方式像文件,但他们没有继承内置文件对象的方法
- #二者都像鸭子,二者看起来都像文件,因而就可以当文件一样去用
- class TxtFile:
- def read(self):
- pass
- def write(self):
- pass
- class DiskFile:
- def read(self):
- pass
- def write(self):
- pass
例2:其实大家一直在享受着多态性带来的好处,比如Python的序列类型有多种形态:字符串,列表,元组,多态性体现如下
- #str,list,tuple都是序列类型
- s=str('hello')
- l=list([1,2,3])
- t=tuple((4,5,6))
- #我们可以在不考虑三者类型的前提下使用s,l,t
- s.__len__()
- l.__len__()
- t.__len__()
- len(s)
- len(l)
- len(t)
四、面向对象高阶
1.重谈封装
(1)封装之如何隐藏属性
- # 隐藏属性实例:
- class A:
- __x = 1 # _A__x=1
- def __init__(self, name):
- self.__name = name # self._A__name=name
- def __foo(self): # def _A__foo(self):
- print('run foo')
- def bar(self):
- self.__foo() # self._A__foo()
- print('from bar')
- print(A.__dict__)
- # 接下来的两句都会报错:
- # print(A.__x)
- # print(A.__foo)
- a = A('egon')
- print(a._A__x)
- print(a._A__foo())
- # 接下来这句也会报错:
- # print(a.__name) # a.__dict__['__name']
- print(a.__dict__)
- a.bar()
- # python实际上是通过使用变形来让这些属性无法被直接访问
- # 这种变形的特点:
- # 1、在类外部无法直接obj.__AttrName
- # 2、在类内部是可以直接使用:obj.__AttrName
- # 3、子类无法覆盖父类__开头的属性
- # 4、这种变形在类定义的阶段就会生成
- # 子类无法覆盖父类__开头的属性:
- class Foo:
- def __func(self): #_Foo__func
- print('from foo')
- class Bar(Foo):
- def __func(self): #_Bar__func
- print('from bar')
- b=Bar()
- b.func()
- # 这种变形需要注意的问题是:
- # (1)这种机制也并没有真正意义上限制我们从外部直接访问属性,知道了类名和属性名就可以拼出名字:_类名__属性,然后就可以访问了,如a._A__N,
- # 即这种操作并不是严格意义上的限制外部访问,仅仅只是一种语法意义上的变形,主要用来限制外部的直接访问
- # (2)变形的过程只在类的定义时发生一次,在定义后的赋值操作,不会变形
- # (3)在继承中,父类如果不想让子类覆盖自己的方法,可以将方法定义为私有
- class B:
- __x = 1
- def __init__(self, name):
- self.__name = name # self._B__name=name
- # 验证问题一:
- print(B._B__x)
- # 验证问题二:
- B.__y = 2
- print(B.__dict__)
- b = B('egon')
- print(b.__dict__)
- b.__age = 18
- print(b.__dict__)
- print(b.__age)
- # 验证问题三:
- class A:
- def foo(self):
- print('A.foo')
- def bar(self):
- print('A.bar')
- self.foo() # self.foo() -> b.foo()
- class B(A):
- def foo(self):
- print('B.foo')
- b = B()
- b.bar()
- class A:
- def __foo(self): # _A__foo
- print('A.foo')
- def bar(self):
- print('A.bar')
- self.__foo() # self._A__foo()
- class B(A):
- def __foo(self): # _B__foo
- print('B.foo')
- b = B()
- b.bar()
(2)封装的意义
封装数据:将数据隐藏起来这不是目的。隐藏起来然后对外提供操作该数据的接口,然后我们可以在接口附加上对该数据操作的限制,以此完成对数据属性操作的严格控制
- # 一:封装数据属性:明确的区分内外,控制外部对隐藏的属性的操作行为
- class People:
- def __init__(self, name, age):
- self.__name = name
- self.__age = age
- def tell_info(self):
- print('Name:<%s> Age:<%s>' % (self.__name, self.__age))
- def set_info(self, name, age):
- if not isinstance(name, str):
- print('名字必须是字符串类型')
- return
- if not isinstance(age, int):
- print('年龄必须是数字类型')
- return
- self.__name = name
- self.__age = age
- # 外部对姓名和年龄的操作只能通过tell_info和set_info这两个函数实现
- p = People('wyb', 21)
- p.tell_info()
- p.set_info('woz', 22)
- p.tell_info()
- # 二、 封装方法:隔离复杂度
- # 取款是功能,而这个功能有很多功能组成:插卡、密码认证、输入金额、打印账单、取钱
- # 对使用者来说,只需要知道取款这个功能即可,其余功能我们都可以隐藏起来,很明显这么做
- # 隔离了复杂度,同时也提升了安全性
- class ATM:
- def __card(self):
- print('插卡')
- def __auth(self):
- print('用户认证')
- def __input(self):
- print('输入取款金额')
- def __print_bill(self):
- print('打印账单')
- def __take_money(self):
- print('取款')
- def withdraw(self):
- self.__card()
- self.__auth()
- self.__input()
- self.__print_bill()
- self.__take_money()
- a = ATM()
- a.withdraw()
2.property
- # BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而非方法,如果我们将其做成一个属性,更便于理解)
- #
- # 成人的BMI数值:
- # 过轻:低于18.5
- # 正常:18.5-23.9
- # 过重:24-27
- # 肥胖:28-32
- # 非常肥胖, 高于32
- #
- # 体质指数(BMI)=体重(kg)÷身高^2(m)
- # EX:70kg÷(1.75×1.75)=22.86
- class BMI:
- def __init__(self, name, weight, height):
- self.name = name
- self.weight = weight
- self.height = height
- @property # 像访问数据一样调用类中函数
- def bmi(self):
- return self.weight / (self.height ** 2)
- p = BMI('egon', 75, 1.81)
- print(p.bmi)
- p.height = 1.82
- print(p.bmi)
- # p.bmi=3333 # 报错AttributeError: can't set attribute
- class People:
- def __init__(self, name):
- self.__name = name
- @property # 像访问数据一样调用类中函数
- def name(self):
- # print('getter')
- return self.__name
- @name.setter # 设置值操作
- def name(self, val):
- # print('setter',val)
- if not isinstance(val, str):
- print('名字必须是字符串类型')
- return
- self.__name = val
- @name.deleter # 删除值操作
- def name(self):
- # print('deleter')
- print('不允许删除')
- p = People('egon')
- print(p.name)
- p.name = 'wyb'
- print(p.name)
- p.name = 123
- del p.name
3.绑定方法与非绑定方法
- # 在类内部定义的函数,分为两大类:
- # 绑定方法:绑定给谁,就应该由谁来调用,谁来调用就回把调用者当作第一个参数自动传入
- # 绑定到对象的方法:在类内定义的没有被任何装饰器修饰的
- # 绑定到类的方法:在类内定义的被装饰器classmethod修饰的方法
- #
- # 非绑定方法:没有自动传值这么一说了,就类中定义的一个普通工具,对象和类都可以使用
- # 非绑定方法:不与类或者对象绑定
- class Foo:
- def __init__(self, name):
- self.name = name
- def tell(self):
- print('名字是%s' % self.name)
- @classmethod
- def func(cls): # cls=Foo
- print(cls)
- @staticmethod
- def func1(x, y):
- print(x + y)
应用:
- import settings
- import hashlib
- import time
- class People:
- def __init__(self, name, age, sex):
- self.id = self.create_id()
- self.name = name
- self.age = age
- self.sex = sex
- def tell_info(self): # 绑定到对象的方法
- print('Name:%s Age:%s Sex:%s' % (self.name, self.age, self.sex))
- @classmethod
- def from_conf(cls):
- obj = cls(
- settings.name,
- settings.age,
- settings.sex
- )
- return obj
- @staticmethod
- def create_id():
- m = hashlib.md5(str(time.time()).encode('utf-8'))
- return m.hexdigest()
- # 绑定给对象,就应该由对象来调用,自动将对象本身当作第一个参数传入
- # p.tell_info() # tell_info(p)
- # 绑定给类,就应该由类来调用,自动将类本身当作第一个参数传入
- # p=People.from_conf() # from_conf(People)
- # p.tell_info()
- # 非绑定方法,不与类或者对象绑定,谁都可以调用,没有自动传值一说
- p1 = People('egon1', 18, 'male')
- p2 = People('egon2', 28, 'male')
- p3 = People('egon3', 38, 'male')
- print(p1.id)
- print(p2.id)
- print(p3.id)
4.反射
- # # 反射:通过字符串映射到对象的属性
- # class People:
- # country = 'China'
- #
- # def __init__(self, name, age):
- # self.name = name
- # self.age = age
- #
- # def talk(self):
- # print('%s is talking' % self.name)
- #
- #
- # obj = People('egon', 18)
- # print(obj.name) # obj.__dict__['name']
- # print(obj.talk)
- # choice = input('>>: ') # choice='name'
- # print(obj.choice) # print(obj.'name') -> 报错
- # python中内置了一些方法可以实现反射:
- # print(hasattr(obj, 'name')) # obj.name # obj.__dict__['name']
- # print(hasattr(obj, 'talk')) # obj.talk
- # print(getattr(obj,'name',None))
- # print(getattr(obj,'talk',None))
- # setattr(obj,'sex','male') # obj.sex='male'
- # print(obj.sex)
- # delattr(obj,'age') # del obj.age
- # print(obj.__dict__)
- # print(getattr(People,'country')) # People.country
- # # 反射的应用:
- # 接受用户输入,根据用户输入选择属性
- class Service:
- def run(self):
- while True:
- inp = input('>>: ').strip() # cmd='get a.txt'
- cmds = inp.split() # cmds=['get','a.txt']
- if hasattr(self, cmds[0]):
- func = getattr(self, cmds[0]) # 获得绑定方法
- func(cmds) # 调用绑定方法
- def get(self, cmds):
- print('get.......', cmds)
- def put(self, cmds):
- print('put.......', cmds)
- obj = Service()
- obj.run()
5.内置方法
- # isinstance(obj,cls)检查是否obj是否是类 cls 的对象
- class Foo(object):
- pass
- obj = Foo()
- isinstance(obj, Foo)
- # issubclass(sub, super)检查sub类是否是 super 类的派生类
- class Foo(object):
- pass
- class Bar(Foo):
- pass
- issubclass(Bar, Foo)
6.元类
(1)exec
- exec:三个参数
- 参数一:字符串形式的命令
- 参数二:全局作用域(字典形式),如果不指定,默认为globals()
- 参数三:局部作用域(字典形式),如果不指定,默认为locals()
- # 可以把exec命令的执行当成是一个函数的执行,会将执行期间产生的名字存放于局部名称空间中
- # 实例如下:
- g={
- 'x':1,
- 'y':2
- }
- l={}
- exec('''
- global x,z
- x=100
- z=200
- m=300
- ''',g,l)
- print(g) # {'x': 100, 'y': 2,'z':200,......}
- print(l) # {'m': 300}
(2)元类介绍
python中一切皆是对象,类本身也是一个对象,当使用关键字class的时候,python解释器在加载class的时候就会创建一个对象(这里的对象指的是类而非类的实例),因而我们可以将类当作一个对象去使用,同样满足第一类对象的概念,可以:
- 把类赋值给一个变量
- 把类作为函数参数进行传递
- 把类作为函数的返回值
- 在运行时动态地创建类
- 可以当作容器类的元素,l=[func,time,obj,1]
- # 类也是对象,Foo=type(....)
- class Foo:
- pass
- obj=Foo()
- print(type(obj))
- print(type(Foo))
元类是类的类,是类的模板,元类是用来控制如何创建类的,正如类是创建对象的模板一样,而元类的主要目的是为了控制类的创建行为
产生类的类称之为元类,默认所有用class定义的类,他们的元类是type,元类用metaclass表示
(3)创建一个类的两种方式
使用class关键字
- class Chinese: # Chinese=type(...)
- country = 'China'
- def __init__(self, namem, age):
- self.name = namem
- self.age = age
- def talk(self):
- print('%s is talking' % self.name)
- # print(Chinese)
- obj = Chinese('woz', 18)
- print(obj, obj.name, obj.age)
使用type的方法手动模拟class创建类的过程,将创建类的步骤拆分开,手动去创建
- # 定义类的三要素:类名,类的基类们,类的名称空间
- class_name = 'Chinese'
- class_bases = (object,)
- class_body = """
- country='China'
- def __init__(self,namem,age):
- self.name=namem
- self.age=age
- def talk(self):
- print('%s is talking' %self.name)
- """
- class_dic = {}
- exec(class_body, globals(), class_dic)
- # print(class_dic)
- Chinese1 = type(class_name, class_bases, class_dic)
- # print(Chinese1)
- obj1 = Chinese1('wyb', 20)
- print(obj1, obj1.name, obj1.age)
(4)自定义元类控制类
- # 自定义元类控制类的行为
- class Mymeta(type):
- def __init__(self, class_name, class_bases, class_dic):
- if not class_name.istitle():
- raise TypeError('类名的首字母必须大写')
- if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
- raise TypeError('必须有注释,且注释不能为空')
- super(Mymeta, self).__init__(class_name, class_bases, class_dic)
- class Chinese(object, metaclass=Mymeta):
- """
- 一个基于自定义元类生成的类,类名首字母必须大写并且必须有注释,且注释不能为空
- """
- country = 'China'
- def __init__(self, namem, age):
- self.name = namem
- self.age = age
- def talk(self):
- print('%s is talking' % self.name)
- # Chinese=Mymeta(class_name,class_bases,class_dic)
- # 自定义元类控制类的实例化行为:
- # 知识储备__call__方法
- # class Foo:
- # def __call__(self, *args, **kwargs):
- # print(self)
- # print(args)
- # print(kwargs)
- #
- #
- # obj = Foo()
- # obj(1, 2, 3, a=1, b=2, c=3) # obj.__call__(obj,1,2,3,a=1,b=2,c=3)
- # 注: 在元类内部也应有有一个__call__方法,会在调用元类时触发执行
- class Mymeta(type):
- def __init__(self, class_name, class_bases, class_dic):
- if not class_name.istitle():
- raise TypeError('类名的首字母必须大写')
- if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
- raise TypeError('必须有注释,且注释不能为空')
- super(Mymeta, self).__init__(class_name, class_bases, class_dic)
- def __call__(self, *args, **kwargs): # obj=Chinese('wyb',age=20)
- # print(self) # self=Chinese
- # print(args) # args=('wyb',)
- # print(kwargs) # kwargs={'wyb': 20}
- # 第一件事:先造一个空对象obj
- obj = object.__new__(self)
- # 第二件事:初始化obj
- self.__init__(obj, *args, **kwargs)
- # 第三件事:返回obj
- return obj
- class Chinese(object, metaclass=Mymeta):
- '''
- 中文人的类
- '''
- country = 'China'
- def __init__(self, namem, age):
- self.name = namem
- self.age = age
- def talk(self):
- print('%s is talking' % self.name)
- obj = Chinese('wyb', age=20) # Chinese.__call__(Chinese,'wyb',20)
- print(obj.__dict__)
- # 单例模式 -> 保证一个类仅有一个实例,并提供一个访问它的全局访问点
- # 实现方式一:
- class MySQL:
- __instance = None # __instance=obj1
- def __init__(self):
- self.host = '127.0.0.1'
- self.port = 3306
- @classmethod
- def singleton(cls):
- if not cls.__instance:
- obj = cls()
- cls.__instance = obj
- return cls.__instance
- def conn(self):
- pass
- def execute(self):
- pass
- obj1 = MySQL.singleton()
- obj2 = MySQL.singleton()
- obj3 = MySQL.singleton()
- print(obj1 is obj2 is obj3)
- # 实现方式二:元类的方式
- class Mymeta(type):
- def __init__(self, class_name, class_bases, class_dic):
- if not class_name.istitle():
- raise TypeError('类名的首字母必须大写')
- if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
- raise TypeError('必须有注释,且注释不能为空')
- super(Mymeta, self).__init__(class_name, class_bases, class_dic)
- self.__instance = None
- def __call__(self, *args, **kwargs): # obj=Chinese('egon',age=18)
- if not self.__instance:
- obj = object.__new__(self)
- self.__init__(obj)
- self.__instance = obj
- return self.__instance
- class Mysql(object, metaclass=Mymeta):
- '''
- mysql xxx
- '''
- def __init__(self):
- self.host = '127.0.0.1'
- self.port = 3306
- def conn(self):
- pass
- def execute(self):
- pass
- obj1 = Mysql()
- obj2 = Mysql()
- obj3 = Mysql()
- print(obj1 is obj2 is obj3)
7.异常处理复习总结
- # 什么是异常:异常是错误发生的信号,一旦程序出错,并且程序没有处理这个错误,那个就会抛出异常,并且程序的运行随之终止
- # 错误分为两种:
- # 语法错误: 使程序无法执行,在程序执行前就要立刻改正过来
- # print('xxxx'
- # if 1 > 2
- # 逻辑错误: 程序逻辑上的错误,在程序运行时才会出现
- #ValueError
- # int('aaa')
- #NameError
- # name
- #IndexError
- # l=[1,2,3]
- # l[1000]
- #KeyError
- # d={}
- # d['name']
- #AttributeError
- # class Foo:
- # pass
- #
- # Foo.xxx
- #ZeroDivisionError:
- # 1/0
- #TypeError:int类型不可迭代
- # for i in 3:
- # pass
- # 异常
- # 强调一:错误发生的条件如果是可以预知的,此时应该用if判断去预防异常
- # AGE=10
- # age=input('>>: ').strip()
- #
- # if age.isdigit():
- # age=int(age)
- # if age > AGE:
- # print('太大了')
- # 强调二:错误发生的条件如果是不可预知的,此时应该用异常处理机制,try...except
- try:
- f=open('a.txt','r',encoding='utf-8')
- print(next(f),end='')
- print(next(f),end='')
- print(next(f),end='')
- print(next(f),end='')
- print(next(f),end='')
- print(next(f),end='')
- print(next(f),end='')
- f.close()
- except StopIteration:
- print('出错啦')
- print('====>1')
- print('====>2')
- print('====>3')
- # 多分支:被监测的代码块抛出的异常有多种可能性,并且我们需要针对每一种异常类型都定制专门的处理逻辑
- # try:
- # print('===>1')
- # # name
- # print('===>2')
- # l=[1,2,3]
- # # l[100]
- # print('===>3')
- # d={}
- # d['name']
- # print('===>4')
- #
- # except NameError as e:
- # print('--->',e)
- #
- # except IndexError as e:
- # print('--->',e)
- #
- # except KeyError as e:
- # print('--->',e)
- #
- # print('====>afer code')
- # 万能异常:Exception,被监测的代码块抛出的异常有多种可能性,
- # 并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception
- # try:
- # print('===>1')
- # # name
- # print('===>2')
- # l=[1,2,3]
- # l[100]
- # print('===>3')
- # d={}
- # d['name']
- # print('===>4')
- #
- # except Exception as e:
- # print('异常发生啦:',e)
- #
- # print('====>afer code')
- # try:
- # print('===>1')
- # # name
- # print('===>2')
- # l=[1,2,3]
- # # l[100]
- # print('===>3')
- # d={}
- # d['name']
- # print('===>4')
- #
- # except NameError as e:
- # print('--->',e)
- #
- # except IndexError as e:
- # print('--->',e)
- #
- # except KeyError as e:
- # print('--->',e)
- #
- # except Exception as e:
- # print('统一的处理方法')
- #
- # print('====>afer code')
- # 其他结构
- # try:
- # print('===>1')
- # # name
- # print('===>2')
- # l=[1,2,3]
- # # l[100]
- # print('===>3')
- # d={}
- # d['name']
- # print('===>4')
- #
- # except NameError as e:
- # print('--->',e)
- #
- # except IndexError as e:
- # print('--->',e)
- #
- # except KeyError as e:
- # print('--->',e)
- #
- # except Exception as e:
- # print('统一的处理方法')
- #
- # else: # 在被检测的代码块没有发生异常时执行
- # pass
- #
- # finally: # 不管被检测的代码块有无发生异常都会执行
- # pass
- #
- # print('====>afer code')
- # 主动触发异常:raise 异常类型(值)
- # class People:
- # def __init__(self,name,age):
- # if not isinstance(name,str):
- # raise TypeError('名字必须传入str类型')
- # if not isinstance(age,int):
- # raise TypeError('年龄必须传入int类型')
- #
- # self.name=name
- # self.age=age
- #
- # p=People('egon',18)
- # 自定义异常类型
- # class MyException(BaseException):
- # def __init__(self, msg):
- # super(MyException, self).__init__()
- # self.msg = msg
- #
- # def __str__(self):
- # return '<%s>' % self.msg
- #
- #
- # raise MyException('我自己的异常类型') # print(obj)
- # 断言assert
- # info={}
- # info['name']='egon'
- # # info['age']=18
- #
- # # if 'name' not in info:
- # # raise KeyError('必须有name这个key')
- # #
- # # if 'age' not in info:
- # # raise KeyError('必须有age这个key')
- #
- # assert ('name' in info) and ('age' in info)
- #
- # if info['name'] == 'egon' and info['age'] > 10:
- # print('welcome')
try-except详细用法
python面向对象重新梳理的更多相关文章
- ~~番外:说说Python 面向对象编程~~
进击のpython Python 是支持面向对象的 很多情况下使用面向对象编程会使得代码更加容易扩展,并且可维护性更高 但是如果你写的多了或者某一对象非常复杂了,其中的一些写法会相当相当繁琐 而且我们 ...
- Python面向对象之:三大特性:继承,封装,多态以及类的约束
前言: python面向对象的三大特性:继承,封装,多态. 1. 封装: 把很多数据封装到⼀个对象中. 把固定功能的代码封装到⼀个代码块, 函数, 对象, 打包成模块. 这都属于封装的思想. 具体的情 ...
- python 面向对象初级篇
Python 面向对象(初级篇) 概述 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发" ...
- Python 面向对象 基础
编程范式概述:面向过程 和 面向对象 以及函数式编程 面向过程:(Procedure Oriented)是一种以事件为中心的编程思想. 就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现 ...
- python面向对象进阶(八)
上一篇<Python 面向对象初级(七)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...
- python 面向对象(进阶篇)
上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...
- python 面向对象编程学习
1. 问题:将所有代码放入一个py文件:无法维护 方案:如果将代码才分放到多个py文件,好处: 1. 同一个名字的变量互相不影响 2.易于维护 3.引用模块: import module 2.包:解决 ...
- Python面向对象详解
Python面向对象的"怜人之处" Python的待客之道--谁能进来 Python的封装--只给你想要的 Python的继承--到处认干爹 Python的多态--说是就是
- python 面向对象和类成员和异常处理
python 面向对象 你把自己想象成一个上帝,你要创造一个星球,首先你要把它揉成一个个球,两个直径就能创造一个球 class star: '''名字(name),赤道直径(equatorial di ...
随机推荐
- 批量读取文件matlab
前言 工程实现的过程中经常需要依次读取文件夹中的图像(或者其他文件),本文就对此进行实现. 代码 % /************************************************ ...
- MP算法、OMP算法及其在人脸识别的应用
主要内容: 1.MP算法 2.OMP算法 3.OMP算法的matlab实现 4.OMP在压缩感知和人脸识别的应用 一.MP(Matching Pursuits)与OMP(Orthogonal Matc ...
- WinRAR备份技巧 - imsoft.cnblogs
RAR控制台日常备份策略 run.batrar a -ep1 -agYYYY{年}MM{月}DD{日} 备份 @list.txt-ep1是忽略原文件路径,rar包里是一堆文件,没有目录结构-ag附加命 ...
- MySQL主从数据库配置
使用工具 MySQL数据版本:5.6.36-log. 两台云服务器(Linux系统) 首先,需要在Linux系统下安装MySQL,具体步骤可以参考这里,并且确保两台主机可以相互访问,可以直接ping一 ...
- Codeforces gym101955 A【树形dp】
LINK 有n个大号和m个小号 然后需要对这些号进行匹配,一个大号最多匹配2个小号 匹配条件是大号和小号构成了前缀关系 字符串长度不超过10 问方案数 思路 因为要构成前缀关系 所以就考虑在trie树 ...
- ACCESS不可识别的数据库格式!
在Access07之前的数据库后缀名均为*.mdb 而连接字符串写成Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myFolder\*.mdb ;Pe ...
- 前端jquery---表单验证
重点: 1.表单的提交 2.触发blur事件 3.判断是否正确,提交与否 return False <!DOCTYPE html> <html lang="en" ...
- 【spring data jpa】好文储备
[spring data jpa]带有条件的查询后分页和不带条件查询后分页实现 : https://blog.csdn.net/lihuapiao/article/details/48782843 ...
- WC游记
第一次来WC,感觉这种集训真吼啊 day0 火车上快速补习了莫队,和AC自动姬,AC自动姬以前就会写只不过太久没写忘了我会了= = 莫队只是学习了做法,还没有做过题…… 本来想再复习一下后缀数组,然后 ...
- 【正则表达式】java应用正则表达式
一:简单应用 /** * * ' * & * ' * & * & * ' * ' * ' * sources=sdcg'hde&xyz'dfa&&ad' ...