20200527----python学习第21天
Posted limin1027
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20200527----python学习第21天相关的知识,希望对你有一定的参考价值。
今日内容
嵌套
特殊方法:__init__
type/isinstance/issubclass/super
异常处理
内容回顾
#函数执行
def login():
pass
login()#执行函数
#类创建对象,调用方法
class Account:
def login(self):
pass
obj = Account()
obj.login()
#1.谈谈你了解的面向对象?
#2.类和对象是什么关系?对象是类创建的一个示例。
class Foo:
def __init__(self,name):
self.name = name
def run(self):
pass
obj1 = Foo(‘alex‘)
obj2 = Foo(‘eric‘)
#3.self是什么?
#self就是一个形式参数,对象调用方法时,python内部会将对象传给这给参数。
class Foo:
def run(self,num):
pass
obj = Foo()
obj.run(5)
#4.类成员&对象成员以及他们的关系
class Foo:
name = ‘alex‘
def run(self):
pass
obj = Foo()
#5.类/方法/对象 都可以当作变量或嵌套到其他类型中。
class Foo:
def run(self):
pass
v = [Foo,Foo,Foo] #列表中存放的是三个类
v2 = [Foo(),Foo(),Foo()] #列表中存放的是三个对象
obj = Foo()
v3 = [obj.run,obj.run,obj.run] #列表中存放的是三个方法
#示例一
class School(object):
def __init__(self,title):
self.title = title
class Course(object):
def __init__(self,name,school_object):
self.name = name
self.school = school_object
class Classes(object):
def __init__(self,cname,course_object):
self.cname = cname
self.course = course_object
s1 = School(‘北京‘)
c1 = Course(‘python‘,s1)
c2 = Course(‘go‘,s1)
cl1 = Classes(‘全栈1期‘,c1)
#示例二
class School(object):
def __init__(self, title):
self.title = title
def rename(self):
pass
class Course(object):
def __init__(self, name, school_object):
self.name = name
self.school = school_object
def reset_price(self):
pass
class Classes(object):
def __init__(self, cname, course_object):
self.cname = cname
self.course = course_object
def sk(self):
pass
详细内容
1.嵌套
函数:参数可以是任意类型。
字典:对象和类都可以做字典的key和value.
继承的查找关系
#示例一
val = 5 + 8
print(val)
#示例二
val2 = ‘alex‘ +‘sb‘
print(val2)
#示例三
class Foo(object):
def __add__(self,other):
return 123
obj1 = Foo() #输出结果为13
obj2 = Foo() #输出结果为alexsb
val3 = obj1 + obj2
print(val3) #输出结果为123
#特殊成员:就是为了能够快速实现执行某些方法而生。
#示例一
class StartConfig(object):
pass
class AdminSite(object):
def __init__(self):
self.data_list = []
def register(self,arg):
self.data_list.append(arg)
site = AdminSite()
obj = StartConfig()
site.register(obj) #StartConfig()对象作为变量存方到data_list列表中
print(site.data_list) #输出内容为:[<__main__.StartConfig object at 0x0000024178C49AC0>]
#示例二
class StartConfig(object):
def __init__(self,name,age):
self.name = name
self.age = age
class AdminSite(object):
def __init__(self):
self.data_list= []
self.sk = None
def set_sk(self,arg):
self.sk = arg
site = AdminSite() #data_list = [] sk= StartConfig
site.set_sk(StartConfig)
site.sk(‘alex‘,19)
#示例三
class StactkConfig(object):
pass
class Foo(object):
pass
class Base(object):
pass
class AdminSite(object):
def __init__(self):
self._register= {}
def registry(self,key,arg):
self._register[key] = arg
site = AdminSite()
site.registry(1,StactkConfig)
site.registry(2,StactkConfig)
site.registry(3,StactkConfig)
site.registry(4,Foo)
site.registry(5,Base)
for k,v in site._register.items():
print(k,v())
#输出结果为:
# 1 <__main__.StactkConfig object at 0x00000298C3CB77F0>
# 2 <__main__.StactkConfig object at 0x00000298C3CB77F0>
# 3 <__main__.StactkConfig object at 0x00000298C3CB77F0>
# 4 <__main__.Foo object at 0x00000298C3CB77F0>
# 5 <__main__.Base object at 0x00000298C3CB77F0>
#示例四
class StackConfig(object):
pass
class UserConfig(StackConfig):
pass
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg = StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
print(key,obj)
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
#输出结果为:
# 1 <__main__.StackConfig object at 0x00000197BE6D8430>
# 2 <__main__.StackConfig object at 0x00000197C02B73A0>
# 3 <__main__.UserConfig object at 0x00000197BE6D8430>
#示例五
class StackConfig(object):
list_display = ‘李绍其‘
class UserConfig(StackConfig):
list_display = ‘利奇航‘
class AdminSite(object):
def __init__(self):
self._register= {}
def registry(self,key,arg = StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
print(key,obj.list_display)
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
#输出结果为:
# 1 李绍其
# 2 李绍其
# 3 利奇航
#示例六
class StackConfig(object):
list_display = ‘李绍其‘
def changelist_view(self):
print(self.list_display)
class UserConfig(StackConfig):
list_display = ‘利奇航‘
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg= StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
obj.changelist_view()
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
#输出结果为:
# 李绍其
# 李绍其
# 利奇航
2.特殊成员
2.1__init__
def Foo:
"""
类是干什么的
:return:
"""
def __init__(self,a1):
"""
初始化
:param self:
:param a1:
:return:
"""
self.a1 = a1
obj = Foo()
2.2__new__
class Foo(object):
def __init__(self):
"""
用户给对象赋值,初始化方法
"""
self.x = 123
def __new__(cls,*args,**kwargs):
"""
用于创建空对象,构建方法
:param args:
:param kwargs:
:return:
"""
return object.__new__(cls)
obj = Foo()
2.3__cal__
class Foo(object):
def __call__(self,*args,**kwargs):
print(‘执行call方法‘)
obj = Foo()
obj() #对象之间调用,是执行call方法
Foo()() #对象之间调用,是执行call方法
#示例二
from wsgiref.simple_server import make_server
def func(environ,start_response):
start_response("200 OK",[(‘Content-Type‘, ‘text/plain; charset=utf-8‘)])
return [‘你好‘.encode(‘utf-8‘)]
class Foo(object):
def __call__(self,environ,start_response):
start_response("200 OK",[(‘Content-Type‘, ‘text/plain; charset=utf-8‘)])
return [‘你<h1 style = "color:red;">好</h1>‘.encode(‘utf-8‘)]
#作用:写一个网站,用户只要来方法,就自动找到第三个参数并执行。
server = make_server(‘127.0.0.1‘,8000,Foo())
server.serve_forever()
2.4__getitem__ __setitem__ __delitem__
class Foo(obect):
def __setitem__(self,key,value):
pass
def __getitem__(self,item):
pass
def __delitem__(self,key):
pass
obj1 = Foo()
obj1[‘k1‘] = 123 #内部会自动调用 __setitem__方法
val = obj1[‘xxx‘] #内部会自动调用__getitem__方法
print(val)
del obj1[‘xxx‘] #内部会自动调用__delitem__方法
2.5__str__
class Foo(object):
def __str__(self):
‘‘‘‘
只有在打印对象时,会自动化调用此方法,并将其返回值在页面显示出来
‘‘‘
return ‘asdfexdfe‘
obj = Foo()
print(obj)
#示例二
class User(object):
def __init__(self,name,email):
self.name = name
self.email = email
def __str__(self):
return "%s %s"%(self.name,self.email)
user_list = [User(‘二狗‘,‘2g@qq.com‘),User(‘二蛋‘,‘3g@qq.com‘),User(‘狗蛋‘,‘9g@qq.com‘)]
for item in user_list:
print(item)
2.6__dict__
class Foo(object):
def __init__(self,name,age,email):
self.name = name
self.age = age
self.email = email
obj = Foo(‘alex‘,19,‘xxx@qq.com‘)
print(obj)
print(obj.name)
print(obj.age)
print(obj.email)
val = obj.__dict__ #去对象中找到所有变量并将其转换为字典
print(val) #val输出结果为:{‘name‘: ‘alex‘, ‘age‘: 19, ‘email‘: ‘xxx@qq.com‘}
2.7上下文管理【面试题】
class Foo(object):
def __init__(self,name,age,email):
self.name = name
self.age = age
self.email = email
obj = Foo(‘alex‘,19,‘xxx@qq.com‘)
print(obj)
print(obj.name)
print(obj.age)
print(obj.email)
val = obj.__dict__ #去对象中找到所有变量并将其转换为字典
print(val) #val输出结果为:{‘name‘: ‘alex‘, ‘age‘: 19, ‘email‘: ‘xxx@qq.com‘}
class Foo(object):
def __enter__(self):
self.x = open(‘a.txt‘,mode = ‘a‘,encoding = ‘utf-8‘)
return self.x
def __exit__(self, exc_type, exc_val, exc_tb):
self.x.close()
with Foo() as ff:
ff.write(‘alex‘)
ff.write(‘alex‘)
ff.write(‘alex‘)
ff.write(‘alex‘)
class Context:
def __enter__(self):
print(‘进入‘)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(‘退出‘)
def do_something(self):
print(‘内部执行1‘)
with Context() as ctx:
print(‘内部执行2‘)
ctx.do_something()
#输出结果为:
# 进入
# 内部执行2
# 内部执行1
# 退出
class Foo(object):
def do_something(self):
print(‘内部执行1‘)
class Context():
def __enter__(self):
print(‘进入‘)
return Foo()
def __exit__(self, exc_type, exc_val, exc_tb):
print(‘退出‘)
with Context() as ctx:
print(‘内部执行2‘)
ctx.do_something()
#输出结果为:
# 进入
# 内部执行2
# 内部执行1
# 退出
2.8两个对象相加
#示例一
val = 5 + 8
print(val)
#示例二
val2 = ‘alex‘ +‘sb‘
print(val2)
#示例三
class Foo(object):
def __add__(self,other):
return 123
obj1 = Foo() #输出结果为13
obj2 = Foo() #输出结果为alexsb
val3 = obj1 + obj2
print(val3) #输出结果为123
#特殊成员:就是为了能够快速实现执行某些方法而生。
3.内置函数补充
3.1type.查看类型
class Foo(object):
pass
obj = Foo()
if type(obj)==Foo:
print(‘obj是Foo类的对象‘)
3.2issubclass
class Base(object):
pass
class Base1(Base):
pass
class Foo(Base1):
pass
class Bar(object):
pass
print(issubclass(Bar,Base)) #False
print(issubclass(Foo,Base1)) #True
print(issubclass(Foo,Base)) #True
3.3isinstance
class Base(object):
pass
class Foo(Base):
pass
obj = Foo()
print(isinstance(obj,Foo)) #True 判断obj是否是Foo类或其基类的示例(对象)
print(isinstance(obj,Base)) #True 判断obj是否是Foo类或其基类的示例(对象)
4.super
#示例一
class MyException(Exception):
pass
try:
raise MyException(‘abcd‘)
except MyException as e:
print(e)
#示例二
class MyException(Exception):
def __init__(self,message):
super().__init__()
self.message = message
try:
raise MyException(Exception)
except MyException as e:
print(e.message)
#示例一
class Base(object):
def func(self):
print(‘base.func‘)
class Foo(Base):
def func(self):
v1 = super().func()
print(‘Foo.func‘,v1)
obj = Foo()
obj.func()
#输出结果为:base.func Foo.func None
#super().func() 去父类中找func方法并执行。
#示例二
# class Bar(object):
# def func(self):
# print(‘bar.func‘)
# return 123
# class Base(Bar):
# pass
# class Foo(Base):
# def func(self):
# v1 = super().func()
# print(‘Foo.func‘,v1)
# obj = Foo()
# obj.func()
# #输出结果为:bar.func Foo.func 123
# #super().func()根据类的继承关系,按照顺序挨个找func方法并执行(找到第一个就不再找了)
#示例三
class Base(object):
def func(self):
super().func()
print(‘base.func‘)
class Bar(object):
def func(self):
print(‘bar.func‘)
class Foo(Base,Bar):
pass
obj = Foo()
obj.func()
#输出结果为:bar.func base.func
#super().func() 根据self对象所属类的继承关系,按照顺序挨个找func方法并执行(找到第一个就不再找了)
5.异常处理
5.1基本格式
try:
pass
except Exception as e:
pass
运行正常的,是不存在异常的,except不能输出e
try:
int(1)
except Exception as e:
print(e)
try:
v = []
v[1111] #IndexError
except ValueError as e:
print(e)
except IndexError as e:
print(e)
except Exception as e:
print(e) #e是Exception类的对象,中有一个错误信息
try:
int(‘abc‘)
except Exception as e:
print(e) #e是Exception类的对象,中有一个错误信息。
finally:
print(‘最后无论对错都会执行‘)
#输出结果为:
# invalid literal for int() with base 10: ‘abc‘
# 最后无论对错都会执行
################################特殊情况
def func():
try:
v= 1
return 123
except Exception as e:
print(e)
return 455
finally:
print(‘最后无论对错都会执行‘)
func()
#输出结果为:
# 最后无论对错都会执行
5.2主动触发异常
try:
int(123)
raise Exception(‘代码有问题,请检查‘) #代码中主动抛出异常
except Exception as e:
print(e)
def func():
result = True
try:
with open(file= "x.log",morde = ‘r‘,encoding = "utf-8") as f:
data = f.read()
if ‘alex‘ not in data:
raise Exception(‘不包含alex关键字‘)
except Exception as e:
result = False
return result
5.3自定义异常
#示例一
class MyException(Exception):
pass
try:
raise MyException(‘abcd‘)
except MyException as e:
print(e)
#示例二
class MyException(Exception):
def __init__(self,message):
super().__init__()
self.message = message
try:
raise MyException(Exception)
except MyException as e:
print(e.message)
总结
特殊成员**
嵌套
type/issubclass/isinstance
super
异常
以上是关于20200527----python学习第21天的主要内容,如果未能解决你的问题,请参考以下文章
ScalersTalk 机器学习小组第 21 周学习笔记(深度学习-10)