一、什么是反射

  反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。

二、四个可以实现自省的函数(下列方法适用于类和对象)

1、hasattr(object,name)

判断object中有没有一个name字符串对应的方法或属性

2、getattr(object, name, default=None)

 获取属性

3、setattr(x, y, v)

 设置属性

4、delattr(x, y)

删除属性

示例:

 class BlackMedium:
feature='Ugly'
def __init__(self,name,addr):
self.name=name
self.addr=addr def sell_house(self):
print('%s 黑中介卖房子啦,傻逼才买呢,但是谁能证明自己不傻逼' %self.name)
def rent_house(self):
print('%s 黑中介租房子啦,傻逼才租呢' %self.name) b1=BlackMedium('万成置地','回龙观天露园') #检测是否含有某属性
print(hasattr(b1,'name'))
print(hasattr(b1,'sell_house')) #获取属性
n=getattr(b1,'name')
print(n)
func=getattr(b1,'rent_house')
func() # getattr(b1,'aaaaaaaa') #报错
print(getattr(b1,'aaaaaaaa','不存在啊')) #设置属性
setattr(b1,'sb',True)
setattr(b1,'show_name',lambda self:self.name+'sb')
print(b1.__dict__)
print(b1.show_name(b1)) #删除属性
delattr(b1,'addr')
delattr(b1,'show_name')
#delattr(b1,'show_name111')#不存在,则报错 print(b1.__dict__)

执行结果:

 True
True
万成置地
万成置地 黑中介房子啦,傻逼才租呢
不存在啊
{'name': '万成置地', 'show_name': <function <lambda> at 0x01142F60>, 'sb': True, 'addr': '回龙观天露园'}
万成置地sb

总结:

hasattr(obj,'属性') #obj.属性 是否存在
getattr(obj,'属性') #获取obj.属性 不存在则报错
getattr(obj,'属性','默认值') #获取obj.属性 不存在不会报错,返回那个默认值
setattr(obj,'属性','属性的值') #obj.属性=属性的值
delattr(obj,'属性') #del obj.属性

三、为什么用反射

有俩程序员,一个alex,一个是egon,alex在写程序的时候需要用到egon所写的类,但是egon去跟女朋友度蜜月去了,还没有完成他写的类,alex想到了反射,使用了反射机制alex可以继续完成自己的代码,等egon度蜜月回来后再继续完成类的定义并且去实现alex想要的功能。

总之反射的好处就是,可以事先定义好接口,接口只有在被完成后才会真正执行,这实现了即插即用,这其实是一种‘后期绑定’,什么意思?即你可以事先把主要的逻辑写好(只定义接口),然后后期再去实现接口的功能

示例:

 class FtpClient:
'ftp客户端,但是还么有实现具体的功能'
def __init__(self,addr):
print('正在连接服务器[%s]' %addr)
self.addr=addr
 #from module import FtpClient
f1=FtpClient('192.168.1.1')
if hasattr(f1,'get'):
func_get=getattr(f1,'get')
func_get()
else:
print('---->不存在此方法')
print('处理其他的逻辑') 不影响alex的代码编写

四、动态导入模块

1、新建一个t.py的文件

 print('---------------->')
def test1():
print('test1') def _test2():
print('test2')

2、再创建:m1文件夹,再在他下面创建一个t.py

 module_t=__import__('m1.t')
print(module_t)
module_t.t.test1()
# from m1.t import *
# from m1.t import test,_test2 import importlib
m=importlib.import_module('m1.t')
print(m)
m.test1()
m._test2()

执行结果:

 ---------------->
<module 'm1' (namespace)>
test1
<module 'm1.t' from 'D:\\python\\day26\\m1\\t.py'>
test1
test2

五、三个参数,给对象添加属性

__setattr__   添加/修改属性会触发它的执行

__delattr__   删除属性的时候会触发

__getattr__   只有在使用点调用属性且属性不存在的时候才会触发

作用:系统内置函数属性(你定义了就用你定义的函数属性,不定义就用系统默认的函数属性)

综合应用示例:

 class Foo:
x=1
def __init__(self,y):
self.y=y def __getattr__(self, item):
print('----> from getattr:你找的属性不存在') def __setattr__(self, key, value):
print('----> from setattr')
# self.key=value #这就无限递归了,你好好想想
# self.__dict__[key]=value #应该使用它 def __delattr__(self, item):
print('----> from delattr')
# del self.item #无限递归了
self.__dict__.pop(item) #__setattr__添加/修改属性会触发它的执行
f1=Foo(10)
print(f1.__dict__) # 因为你重写了__setattr__,凡是赋值操作都会触发它的运行,你啥都没写,就是根本没赋值,除非你直接操作属性字典,否则永远无法赋值
f1.z=3
print(f1.__dict__) #__delattr__删除属性的时候会触发
f1.__dict__['a']=3#我们可以直接修改属性字典,来完成添加/修改属性的操作
del f1.a
print(f1.__dict__) #__getattr__只有在使用点调用属性且属性不存在的时候才会触发
f1.xxxxxx

分开应用:

示例1:__getattr__(重点,因为常用)

 class Foo:
x=1
def __init__(self,y):
self.y=y def __getattr__(self, item):
print('执行__getattr__') f1=Foo(10)
print(f1.y) #没有的时候就会触发: __getattr__
print(getattr(f1,'y')) #len(str)---->str.__len__()
f1.ssssssssssssssssssssssssssssss

执行结果:

 10
10
执行__getattr__

示例2:__delattr__(不常用)

 class Foo:
x=1
def __init__(self,y):
self.y=y def __delattr__(self, item):
print('删除操作__delattr__') f1=Foo(10)
del f1.y
del f1.x

执行结果:

 删除操作__delattr__
删除操作__delattr__

示例3: __setattr__(不常用)

 class Foo:
x=1
def __init__(self,y):
self.y=y def __setattr__(self,key,value):
print('__setattr__执行')
#self.key=value
self.__dict__[key]=value #增加键、值到字典中
f1=Foo(10)
print(f1.__dict__) f1.z=2
print(f1.__dict__)

执行结果:

 __setattr__执行
{'y': 10}
__setattr__执行
{'z': 2, 'y': 10}

总结:

obj点的方式去操作属性时触发的方法

__getattr__:obj.属性 不存在时触发
__setattr__:obj.属性=属性的值 时触发
__delattr__:del obj.属性 时触发

六、二次加工标准类型(包装)

包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们刚学的继承/派生知识(其他的标准类型均可以通过下面的方式进行二次加工)。

 class List(list):
def append(self, p_object):
'我改写的方法'
if not isinstance(p_object,str):
print('只有字符串类型能被添加到列表中')
return
# self.append(p_object) #进入无限递归
super().append(p_object)
def show_mid(self):
'我新增的方法'
index=int(len(self)/2)
print(self[index]) l1=List('hello') l1.append('abc')
print(l1,type(l1)) #数字无法添加成功
l1.append(1)
print('-->',l1) #基于标准类型新增了功能
l1.show_mid()

授权:授权是包装的一个特性, 包装一个类型通常是对已存在的类型的一些定制,这种做法可以新建,修改或删除原有产品的功能。其它的则保持原样。授权的过程,即是所有更新的功能都是由新类的某部分来处理,但已存在的功能就授权给对象的默认属性。

实现授权的关键点就是覆盖__getattr__方法

1、通过触发__getattr__方法,找到read方法

示例1:

 import time
class FileHandle:
def __init__(self,filename,mode='r',encoding='utf-8'):
self.file=open(filename,mode,encoding=encoding)
self.mode=mode
self.encoding=encoding def __getattr__(self, item):
print(item,type(item))
self.file.read #self.file里面有read方法
return getattr(self.file,item) #能过字符串来找到,并通过return返回,就找到了read方法, f1=FileHandle('a.txt','r')
print(f1.file)
print(f1.__dict__) #类的字典里,没有read方法,就触发了__getattr__方法
print(f1.read) #找到了read方法 sys_f=open('b.txt','w+')
print('---->',getattr(sys_f,'read')) #找到了read方法

执行结果:

 <_io.TextIOWrapper name='a.txt' mode='r' encoding='utf-8'>

 read <class 'str'>

 <built-in method read of _io.TextIOWrapper object at 0x01638EB0>

 {'encoding': 'utf-8', 'file': <_io.TextIOWrapper name='a.txt' mode='r' encoding='utf-8'>, 'mode': 'r'}

 ----> <built-in method read of _io.TextIOWrapper object at 0x01638F30>

2、往文件里面写入内容

示例2:

 import time
class FileHandle:
def __init__(self,filename,mode='r',encoding='utf-8'):
# self.filename=filename
self.file=open(filename,mode,encoding=encoding)
self.mode=mode
self.encoding=encoding
def write(self,line):
print('------------>',line)
t=time.strftime('%Y-%m-%d %X')
self.file.write('%s %s' %(t,line)) def __getattr__(self, item):
# print(item,type(item))
# self.file.read
return getattr(self.file,item) f1=FileHandle('a.txt','w+')
f1.write('1111111111111111\n')
f1.write('cpu负载过高\n')
f1.write('内存剩余不足\n')
f1.write('硬盘剩余不足\n')

执行结果:

会创建一个a.txt的文件,并往里面写入内容:

 2016-12-23 18:34:16 1111111111111111
2016-12-23 18:34:16 cpu负载过高
2016-12-23 18:34:16 内存剩余不足
2016-12-23 18:34:16 硬盘剩余不足

七、isinstance(obj,cls)和issubclass(sub,super)

1、isinstance(obj,cls) 检查是否obj是否是类cls的对象

示例:

 class Foo(object):
pass obj = Foo() print(isinstance(obj,Foo))

执行结果:

1 True

2、issubclass(sub,super)检查sub类是否是supper类的派生类

示例:

 class Foo(object):
pass class Bar(Foo):
pass print(issubclass(Bar,Foo))

执行结果:

 True

八、__getattribute__

示例1:

不存在的属性访问,就会触发__getattr__方法

 class Foo:
def __init__(self,x):
self.x=x def __getattr__(self, item):
print('执行的是我')
#return self.__idct__[item] f1=Foo(10)
print(f1.x)
f1.xxxxxx #不存在的属性访问,触发__getattr__

执行结果:

 10
执行的是我

示例2:

不管是否存在,都会执行__getattribute__方法

 class Foo:
def __init__(self,x):
self.x=x def __getattribute__(self, item):
print('不管是否存在,我都会执行') f1=Foo(10)
f1.x
f1.xxxxxxx

执行结果:

 不管是否存在,我都会执行
不管是否存在,我都会执行

示例:3:

 class Foo:
def __init__(self,x):
self.x=x def __getattr__(self, item): #相当于监听大哥的异常,大哥抛出导常,他就会接收。
print('执行的是我')
# return self.__dict__[item] def __getattribute__(self, item):
print('不管是否存在,我都会执行')
raise AttributeError('抛出异常了') f1=Foo(10)
f1.x #结果是:10 ,调用会触发系统的
f1.xxxxxxx #如果不存在会触发自己定义的

执行结果:

 不管是否存在,我都会执行
执行的是我
不管是否存在,我都会执行
执行的是我

九、__setitem__,__getitem,__delitem__  (操作字典就用item的方式)

obj[‘属性’]的方式去操作属性时触发的方法

__getitem__:obj['属性'] 时触发
__setitem__:obj['属性']=属性的值 时触发
__delitem__:del obj['属性'] 时触发

示例1:

 class Foo:

     def __getitem__(self, item):
print('getitem',item)
return self.__dict__[item] def __setitem__(self, key, value):
print('setitem')
self.__dict__[key]=value def __delitem__(self, key):
print('delitem')
self.__dict__.pop(key) f1=Foo()
print(f1.__dict__)
f1['name']='agon'
f1['age']=18
print('====>',f1.__dict__) del f1['name']
print(f1.__dict__) print(f1,['age'])

执行结果:

 {}

 setitem

 setitem

 ====> {'age': 18, 'name': 'agon'}

 delitem

 {'age': 18}

 <__main__.Foo object at 0x01DC4150> ['age']

示例2:

 class Foo:
def __init__(self,name):
self.name=name def __getitem__(self, item):
print(self.__dict__[item]) def __setitem__(self, key, value):
self.__dict__[key]=value
def __delitem__(self, key):
print('del obj[key]时,我执行')
self.__dict__.pop(key)
def __delattr__(self, item):
print('del obj.key时,我执行')
self.__dict__.pop(item) f1=Foo('sb')
f1['age']=18
f1['age1']=19
del f1.age1
del f1['age']
f1['name']='alex'
print(f1.__dict__)

执行结果:

 del obj.key时,我执行

 del obj[key]时,我执行

 {'name': 'alex'}

十、__str__, __repr__,__format__

1、改变对象的字符串显示__str__,__repr__  (只能是字符串的值,不能是非字符串的值)

示例1:

 l = list('hello')
print(1) file=open('test.txt','w')
print(file)

执行结果:

 1
<_io.TextIOWrapper name='test.txt' mode='w' encoding='cp936'>

示例2:

__str__方法

 #自制str方法
class Foo:
def __init__(self,name,age):
self.name=name
self.age=age def __str__(self):
return '名字是%s 年龄是%s' %(self.name,self.age) f1=Foo('age',18)
print(f1) #str(f1)---->f1.__str__() x=str(f1)
print(x) y=f1.__str__()
print(y)

执行结果:

 名字是age 年龄是18
名字是age 年龄是18
名字是age 年龄是18

示例3:

__repe__方法

 #触发__repr__方法,用在解释器里输出
class Foo:
def __init__(self,name,age):
self.name=name
self.age=age def __repr__(self):
return '名字是%s 年龄是%s' %(self.name,self.age) f1=Foo('agon',19)
print(f1)

执行结果:

 名字是agon 年龄是19

示例4:

__str__和__repe__ 共存时的用法

 # 当str与repr共存时
class Foo:
def __init__(self,name,age):
self.name=name
self.age=age def __str__(self):
return '名字是%s 年龄是%s' % (self.name,self.age) def __repr__(self):
return '名字是%s 年龄是%s' %(self.name,self.age) f1=Foo('egon',19)
#repr(f1)--->f1.__repr__()
print(f1) #str(f1)--->f1.__str__()---->f1.__repr__()
执行结果:
 <__main__.Foo object at 0x018E10B0>

总结:

str函数或者print函数--->obj.__str__()
repr或者交互式解释器--->obj.__repr__()
如果__str__没有被定义,那么就会使用__repr__来代替输出
注意:这俩方法的返回值必须是字符串,否则抛出异常 

2、自定制格式化字符串__format__

format的用法

示例1:

 x = '{0}{0}{0}'.format('dog')
print(x)

执行结果:

 dogdogdog

不用__format__的方式实现

示例2:

 class Date:
def __init__(self,year,mon,day):
self.year=year
self.mon=mon
self.day=day d1=Date(2016,12,26) x = '{0.year}{0.mon}{0.day}'.format(d1)
y = '{0.year}:{0.mon}:{0.day}'.format(d1)
z = '{0.year}-{0.mon}-{0.day}'.format(d1)
print(x)
print(y)
print(z)

执行结果:

 20161226
2016:12:26
2016-12-26

用__format__的方式实现

示例3:

 format_dic={
'ymd':'{0.year}:{0.month}:{0.day}',
'm-d-y':'{0.month}-{0.day}-{0.year}',
'y:m:d':'{0.year}:{0.month}:{0.day}',
} class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day def __format__(self, format_spec):
print('我执行啦')
print('----->',format_spec)
if not format_spec or format_spec not in format_dic:
format_spec='ymd'
fmt=format_dic[format_spec]
return fmt.format(self) d1=Date(2016,12,29)
# print(format(d1)) #d1.__format__()
# print(format(d1)) print(format(d1,'ymd'))
print(format(d1,'y:m:d'))
print(format(d1,'m-d-y'))
print(format(d1,'m-d:y'))
print('===========>',format(d1,'sdsdddsfdsfdsfdsfdsfsdfdsfsdfds'))

执行结果:

 我执行啦
-----> ymd
2016:12:29
我执行啦
-----> y:m:d
2016:12:29
我执行啦
-----> m-d-y
12-29-2016
我执行啦
-----> m-d:y
2016:12:29
我执行啦
-----> sdsdddsfdsfdsfdsfdsfsdfdsfsdfds
===========> 2016:12:29

十一、 __slots__  (慎用)

1.__slots__是什么?是一个类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性)

2.引子:使用点来访问属性本质就是在访问类或者对象的__dict__属性字典(类的字典是共享的,而每个实例的是独立的)

3.为何使用__slots__:字典会占用大量内存,如果你有一个属性很少的类,但是有很多实例,为了节省内存可以使用__slots__取代实例的__dict__ 当你定义__slots__后,__slots__就会为实例使用一种更加紧凑的内部表示。实例通过一个很小的固定大小的数组来构建,而不是为每个实例定义一个 字典,这跟元组或列表很类似。在__slots__中列出的属性名在内部被映射到这个数组的指定小标上。使用__slots__一个不好的地方就是我们不能再给 实例添加新的属性了,只能使用在__slots__中定义的那些属性名。

4.注意事项:__slots__的很多特性都依赖于普通的基于字典的实现。另外,定义了__slots__后的类不再 支持一些普通类特性了,比如多继承。大多数情况下,你应该 只在那些经常被使用到 的用作数据结构的类上定义__slots__比如在程序中需要创建某个类的几百万个实例对象 。 关于__slots__的一个常见误区是它可以作为一个封装工具来防止用户给实例增加新的属性。尽管使用__slots__可以达到这样的目的,但是这个并不是它的初衷。更多的是用来作为一个内存优化工具。

__slots__的作用:节省内存空间

1、一个key的情况

示例1:

 #__slots__  (作用:就是节省内存)
#一个key的值 class Foo:
__slots__='name' #定义在类中的类变量,由这个类产生的实例,不在具有__dict__的属性字典,限制了创建属性 f1=Foo()
f1.name='agon'
print(f1.name) #只能有一个name属性
print(Foo.__slots__)
print(f1.__slots__)

执行结果:

 agon
name
name

2、两个key的情况

示例2:

 #两个key的情况
class Foo:
__slots__=['name','age'] f1=Foo() print(Foo.__slots__)
print(f1.__slots__)
f1.name='egon'
f1.age=17
print(f1.name)
print(f1.age)
# f1.gender='male' #会报错,加不上,#AttributeError: 'Foo' object has no attribute 'gender' #只能定义__slots__提供的属性(这里就定义了两个属性)大家都用一个属性字典,优势就是节省内存
f2=Foo()
print(f2.__slots__)
f2.name='alex'
f2.age=18
print(f2.name)
print(f2.age)

执行结果:

 ['name', 'age']
['name', 'age']
egon
17
['name', 'age']
alex
18

十二、__doc__

1、它类的描述信息

示例:

 class Foo:
'我是描述信息'
pass print(Foo.__doc__)

2、该属性无法继承

示例:

 #__doc__ 该属性无法继承

 class Foo:
pass class Bar(Foo):
pass print(Foo.__dict__) #只要加上了__doc__,该属性就无法继承给子类
print(Bar.__dict__) #原理就是在底层字典里面,会加一个'__doc__': None,

十三、__module__和__class__

  __module__ 表示当前操作的对象在那个模块

  __class__     表示当前操作的对象的类是什么

1、创建lib/aa.py

 #!/usr/bin/env python
# -*- coding:utf-8 -*- class C: def __init__(self):
self.name = ‘SB' lib/aa.py

2、输出模块和输出类

 from lib.aa import C

 obj = C()
print obj.__module__ #输出 lib.aa,即:输出模块
print obj.__class__ #输出 lib.aa.C,即:输出类

十四、__del__ 析构方法(垃圾回收时自动触发)

  析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

 class Foo:
def __init__(self,name):
self.name=name
def __del__(self):
print('我执行啦') f1=Foo('alex') #del f1 #删除实例会触发__del__
del f1.name #删除实例的属性不会触发__del__
print('---------------->')

执行结果:

 ---------------->
我执行啦

十五、__call__

示例:

 class Foo:
def __call__(self, *args, **kwargs):
print('实例执行啦 obj()') f1=Foo() #Foo下的__call__ f1() #abc下的__call__

执行结果:

 实例执行啦 obj()

十六、 __next__和__iter__实现迭代器协议

一、什么是迭代器协议

1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前退)

2.可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义一个__iter__()方法)

3.协议是一种约定,可迭代对象实现了迭代器协议,python的内部工具(如for循环,sum,min,max函数等)使用迭代器协议访问对象。

二、python中强大的for循环机制

for循环的本质:循环所有对象,全都是使用迭代器协议。

(字符串,列表,元组,字典,集合,文件对象)这些都不是可迭代对象,只不过在for循环式,调用了他们内部的__iter__方法,把他们变成了可迭代对象

然后for循环调用可迭代对象的__next__方法去取值,而且for循环会捕捉StopIteration异常,以终止迭代。

示例1:

 #迭代器协议

 class Foo:
pass l = list('hello')
for i in l: #for循环本质就是调用他:f1.__iter__() == iter(f1)
print(i)

执行结果:

 h
e
l
l
o

示例2:

 class Foo:
def __init__(self,n):
self.n=n def __iter__(self): #把一个对象就成一个可迭代对象,必须有__iter__
return self def __next__(self):
self.n+=1
return self.n f1=Foo(10)
# for i in f1: #for循环本质就是调用他:f1.__iter__() == iter(f1)
# print(i) print(f1.__next__())
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1)) for i in f1: #for循环本质就是调用他:f1.__iter__() == iter(f1)
print(i)

执行结果:

 11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
会一直无限循环下去.....
下面部分省略.....

示例3:

 class Foo:
def __init__(self,n):
self.n=n def __iter__(self): #把一个对象就成一个可迭代对象,必须有__iter__
return self def __next__(self):
if self.n == 13:
raise StopIteration('终止了')
self.n+=1
return self.n f1=Foo(10) # print(f1.__next__())
# print(f1.__next__())
# print(f1.__next__())
# print(f1.__next__()) for i in f1: #f1.__iter__() == iter(f1)
print(i) #obj.__next__()

执行结果:

 11
12
13

三、斐波那契数列

什么是斐波那契数列?

  斐波那契数列指的是这样一个数列 1, 1, , 3, 5, , 13, 21, , 55, 89, , 233,377,,987,1597,,4181,6765,........
这个数列从第3项开始,每一项都等于前两项之和。
 
示例1:

1 1 2 (相当于1+1=2) #后面这个数是前两个数之和

3 5 8 (相当于3+5=8)   #后面这个数是前两个数之和

用迭代器协议的方法实现:一次产生一个值

示例2:

 #斐波那契数列
class Fib:
def __init__(self):
self._a=1
self._b=1 def __iter__(self):
return self
def __next__(self):
if self._a > 100:
raise StopIteration('终止了') # >100 就抛出异常
self._a,self._b=self._b,self._a + self._b #1+1=b; a,b=b,a(等于交换值)
return self._a f1=Fib()
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print('==================================')
for i in f1:
print(i)

执行结果:

 1
2 5
8 #print(next(f1))
==================================
13 #for循环的值
21 55
89

十七、描述符(__get__,__set__,__delete__)  (新式类中描述符在大型开发中常用,必须掌握。)

描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()三个方法中的一个,这也被称为描述符协议。

 class 描述符:
def __get__():
pass
def __set__():
pass
def __delete__():
pass class 类:
name=描述符() obj=类()
obj.name #get方法
obj.name='egon' #set方法
del obj.name #delete

描述符的三种方法:

__get__():  .调用一个属性时,触发
__set__():   .为一个属性赋值时,触发
__delete__():  采用del.删除属性时,触发

1、定义一个描述符

示例1:

 class Foo:   #在python3中Foo是新式类,它实现了三种方法,这个类就被称作一个描述符
def __get__(self,instance,owner):
print('get方法')
def __set__(self, instance, value):
print('set方法')
def __delete__(self, instance):
print('delete方法')

2、描述符是干什么的:描述符的作用是用来代理另外一个类的属性的(必须把描述符定义成这个类的类属性,不能定义到构造函数中)

示例2:

 class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') #包含这三个方法的新式类称为描述符,由这个类产生的实例进行属性的调用/赋值/删除,并不会触发这三个方法
f1=Foo()
f1.name='egon'
print(f1.name)
del f1.name
#疑问:何时,何地,会触发这三个方法的执行

3、描述符应用之何时?何地?

示例3:

 #描述符应用之何时?何地?

 #描述符Str
class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') class Bar:
x=Foo() #在何地? print(Bar.__dict__) #在何时?
b1=Bar()
# b1.x #调用就会触发上面的get方法
# b1.x=1 #赋值
# del b1.x
print(b1.x) #触发了描述器里面的get方法,得到None
b1.x=1 #触发了描述器里面的set方法,得到{}
print(b1.__dict__) #写到b1的属性字典中 del b1.x #打印===>delete方法

执行结果:

 {'x': <__main__.Foo object at 0x014210D0>, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__dict__': <attribute '__dict__' of 'Bar' objects>, '__doc__': None, '__module__': '__main__'}

 ===>get方法

 None

 ===>set方法

 {}

 ===>delete方法

4、描述符分两种

一、数据描述符:至少实现了__get__()和__set__()两种方法

示例:

1 class Foo:
2 def __set__(self, instance, value):
3 print('set')
4 def __get__(self, instance, owner):
5 print('get')

二、非数据描述符:没有实现__set__()方法

示例:

1 class Foo:
2 def __get__(self, instance, owner):
3 print('get')

5、注意事项:
一、描述符本身应该定义成新式类,被代理的类也应该是新式类
二、必须把描述符定义成另外一个类触发的类属性,不能为定义到构造函数中

示例:

 class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') class Bar:
x=Foo() #定义一个描述符
def __init__(self,n):
self.x=n b1=Bar(10) #触发set方法
print(b1.__dict__)

执行结果:

 ===>set方法
{}

三、要严格遵循该优先级,优先级由高到底分别是
1.类属性
2.数据描述符
3.实例属性
4.非数据描述符
5.找不到的属性触发__getattr__()

类属性>数据描述符

示例:

 class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') class Bar:
x=Foo() #调用foo()属性,会触发get方法 print(Bar.x) #类属性比描述符有更高的优先级,会触发get方法
Bar.x=1 #自己定义了一个类属性,并赋值给x,跟描述符没有关系,所以他不会触发描述符的方法
# print(Bar.__dict__)
print(Bar.x)

执行结果:

 ===>get方法
None
1

数据描述符>实例属性

示例1:

 #有get,set就是数据描述符,数据描述符比实例属性有更高的优化级

 class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') class Bar:
x = Foo() # 调用foo()属性,会触发get方法 b1=Bar() #在自己的属性字典里面找,找不到就去类里面找,会触发__get__方法
b1.x #调用一个属性的时候触发get方法
b1.x=1 #为一个属性赋值的时候触发set方法
del b1.x #采用del删除属性时触发delete方法

执行结果:

 1 ===>get方法
2 ===>set方法
3 ===>delete方法

示例2:

 class Foo:
def __get__(self,instance,owner):
print('===>get方法') def __set__(self, instance, value):
pass class Bar:
x = Foo() b1=Bar()
b1.x=1 #触发的是非数据描述符的set方法
print(b1.__dict__)

执行结果:

 {}   #数据描述符>实例属性

类属性>数据描述符>实例属性

 #类属性>数据描述符>实例属性

 class Foo:
def __get__(self,instance,owner):
print('===>get方法')
def __set__(self, instance, value):
print('===>set方法')
def __delete__(self, instance):
print('===>delete方法') class Bar:
x = Foo() #调用foo()属性,会触发get方法 b1=Bar() #实例化
Bar.x=11111111111111111 #不会触发get方法
b1.x #会触发get方法 del Bar.x #已经给删除,所以调用不了!报错:AttributeError: 'Bar' object has no attribute 'x'
b1.x

非数据描述符

示例1:

 #非数据描述符没有set方法
class Foo:
def __get__(self,instance,owner):
print('===>get方法') def __delete__(self, instance):
print('===>delete方法') class Bar:
x = Foo() b1=Bar()
b1.x #自己类中没有,就会去Foo类中找,所以就会触发__get__方法

执行结果:

===>get方法

示例2:

 #实例属性>非数据描述符
class Foo:
def __get__(self,instance,owner):
print('===>get方法') class Bar:
x = Foo() b1=Bar()
b1.x=1
print(b1.__dict__) #在自己的属性字典里面,{'x': 1}

执行结果:

 {'x': 1}

非数据描述符>找不到

 #非数据描述符>找不到

 class Foo:
def __get__(self,instance,owner):
print('===>get方法') class Bar:
x = Foo()
def __getattr__(self, item):
print('------------>') b1=Bar()
b1.xxxxxxxxxxxxxxxxxxx #调用没有的xxxxxxx,就会触发__getattr__方法

执行结果:

 ------------>    #解发__getattr__方法

四、描述符应用

示例1:

 class Typed:   #有__get__,__set__,__delete__ 就是:数据描述符
def __get__(self, instance,owner):
print('get方法')
print('instance参数【%s】' %instance)
print('owner参数【%s】' %owner) def __set__(self, instance, value):
print('set方法')
print('instance参数【%s】' %instance)
print('value参数【%s】' %value) def __delete__(self, instance):
print('delete方法')
print('instance参数【%s】'% instance) class People:
name=Typed() #设置代理(代理的就是name属性)
def __init__(self,name,age,salary):
self.name=name #触发的是代理
self.age=age
self.salary=salary p1=People('alex',13,13.3)
#'alex' #触发set方法
p1.name #触发get方法,没有返回值
p1.name='age' #触发set方法
print(p1.__dict__) #{'salary': 13.3, 'age': 13}

执行结果:

 set方法
instance参数【<__main__.People object at 0x006110F0>】
value参数【alex】
get方法
instance参数【<__main__.People object at 0x006110F0>】
owner参数【<class '__main__.People'>】
set方法
instance参数【<__main__.People object at 0x006110F0>】
value参数【age】
{'salary': 13.3, 'age': 13}

示例2:给字典属性传值

 #给字典里面传入值
class Typed:
def __init__(self,key):
self.key=key def __get__(self, instance, owner):
print('get方法')
return instance.__dict__[self.key] #触发get方法,会返回字典的值 def __set__(self, instance, value):
print('set方法')
instance.__dict__[self.key]=value #存在p1的属性字典里面 def __delete__(self, instance):
print('delete方法')
instance.__dict__.pop(self.key) class People:
name=Typed('name') #name属性被Typed给代理了,t1._set_() self._set__()
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary p1=People('alex',13,13.3) #打印实例字典
print(p1.__dict__) #创建属性,给name赋值,相当于修改了name字典的值
p1.name='egon' #触发的是set方法
print(p1.__dict__) #删除name属性
print(p1.__dict__)
del p1.name #触发的是delete方法
print(p1.__dict__)

执行结果:

 #打印实例属性字典
set方法
{'age': 13, 'salary': 13.3, 'name': 'alex'} #修改name字典的值
set方法
{'age': 13, 'salary': 13.3, 'name': 'egon'} #删除name属性
delete方法
{'age': 13, 'salary': 13.3}

示例3:

实现类型检测的两种方法:

方法一:用return的方式

 #判断他传入的值是不是字符串类型
class Typed:
def __init__(self,key):
self.key=key def __get__(self, instance, owner):
print('get方法')
return instance.__dict__[self.key] #触发get方法,会返回字典的值 def __set__(self, instance, value):
print('set方法')
if not isinstance(value,str):
print('你传入的类型不是字符串,错误')
return #return的作用就是终止这个属性字典,让他的值设置不进字典中。
instance.__dict__[self.key]=value #存在p1的属性字典里面 def __delete__(self, instance):
print('delete方法')
instance.__dict__.pop(self.key) class People:
name=Typed('name') #name属性被Typed给代理了,t1._set_() self._set__()
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary #正常的情况下__dict__里面有没有'name':'alex'
p1=People('alex',13,13.3)
print(p1.__dict__) #触发set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13} #不正常的情况下,修改'name':213 不等于字符串,改成了int类型
p1=People(213,13,13.3)
print(p1.__dict__) #触发set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

执行结果:

 set方法
{'salary': 13.3, 'age': 13, 'name': 'alex'} set方法
你传入的类型不是字符串,错误
{'salary': 13.3, 'age': 13}

方法二:用raise抛出异常的方式,判断他传入的值是不是字符串类型,(写死了,不灵活)

 #用抛出异常的方式,判断他传入的值是不是字符串类型
class Typed:
def __init__(self,key):
self.key=key def __get__(self, instance, owner):
print('get方法')
return instance.__dict__[self.key] #触发get方法,会返回字典的值 def __set__(self, instance, value):
print('set方法')
if not isinstance(value,str): #判断是否是字符串类型
#方法一:return的方式
14 # print('你传入的类型不是字符串,错误')
15 # return #return的作用就是终止这个属性字典,让他的值设置不进字典中。
16 #方法二:
raise TypeError('你传入的类型不是字符串') ##用抛出异常的方式,判断他传入的值是不是字符串类型
instance.__dict__[self.key]=value #存在p1的属性字典里面 def __delete__(self, instance):
print('delete方法')
instance.__dict__.pop(self.key) class People:
name=Typed('name') #name属性被Typed给代理了,t1._set_() self._set__()
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary #正常的情况下__dict__里面有没有'name':'alex'
# p1=People('alex',13,13.3)
# print(p1.__dict__) #触发set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13} #不正常的情况下,修改'name':213 不等于字符串,改成了int类型
p1=People(213,13,13.3)
print(p1.__dict__) #触发set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

执行结果:

 Traceback (most recent call last):
set方法
File "D:/python/day28/5-1.py", line 219, in <module>
{'name': 'alex', 'age': 13, 'salary': 13.3}
set方法
p1=People(213,13,13.3)
File "D:/python/day28/5-1.py", line 210, in __init__
self.name=name
File "D:/python/day28/5-1.py", line 200, in __set__
raise TypeError('你传入的类型不是字符串')
TypeError: 你传入的类型不是字符串

类型检测加强版

示例:4:用raise抛出异常的方式,判断传入的值是什么类型,同时可以判断多个属性  (推荐写法)

 #用抛出异常的方式,判断他传入的值是什么类型  (不写死的方式,判断传入值的类型)
class Typed:
def __init__(self,key,expected_type):
self.key=key
self.expected_type=expected_type def __get__(self, instance, owner):
print('get方法')
return instance.__dict__[self.key] #触发get方法,会返回字典的值 def __set__(self, instance, value):
print('set方法')
if not isinstance(value,self.expected_type):
raise TypeError('%s 你传入的类型不是%s' %(self.key,self.expected_type)) #用抛出异常的方式,判断他传入的值是什么类型,同时可以判断多个属性的类型
instance.__dict__[self.key]=value #存在p1的属性字典里面 def __delete__(self, instance):
print('delete方法')
instance.__dict__.pop(self.key) class People:
name=Typed('name',str) #name设置代理Typed
23 age=Typed('age',int) #age设置代理Typed
def __init__(self,name,age,salary):
self.name=name #alex传给代理,会触发set方法
self.age=age #age传给代理,会触发set方法
self.salary=salary #name是字符串,age是整型,salary必须是浮点数
#正确的方式
p1=People('alex',13,13.3) #传入错误的类型,会判断传入值的类型
#name要求传入的srt,但这里传入的是整型,所以会报错,说你传入的不是srt类型
p1=People(,13,13.3)

执行结果:

 set方法
File "D:/python/day28/5-1.py", line 220, in <module>
p1=People(213,13,13.3)
set方法
File "D:/python/day28/5-1.py", line 210, in __init__
set方法
self.name=name
File "D:/python/day28/5-1.py", line 199, in __set__
raise TypeError('%s 你传入的类型不是%s' %(self.key,self.expected_type)) #用抛出异常的方式,判断他传入的值是什么类型 TypeError: name 你传入的类型不是<class 'str'>

十八、__enter__和__exit__

1、操作文件写法

1 with open('a.txt') as f:
2   '代码块'

2、上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法

 class Open:
def __init__(self,name):
self.name=name def __enter__(self):
print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')
# return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('with中代码块执行完毕时执行我啊') with Open('a.txt') as f: #with语句,触发__enter__,返回值赋值给f
print('=====>执行代码块')
# print(f,f.name)

执行结果:

 出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊

3、执行代码块

__exit__()中的三个参数分别代表异常类型,异常值和追溯信息,with语句中代码块出现异常,则with后的代码都无法执行

没有异常的情况下,整个代码块运行完毕后去触发__exit__,它的三个参数都会执行

 class Foo:
def __init__(self,name):
self.name=name def __enter__(self):
print('执行enter')
return self #2、拿到的结果是self,并赋值给f def __exit__(self, exc_type, exc_val, exc_tb): #4、触发__exit__,然后执行print()
print('执行exit')
print(exc_type)
print(exc_val)
print(exc_tb) with Foo('a.txt') as f: #1、with触发的是__enter__,拿到的结果是self并赋值给f;
print(f) #3、然后会执行with代码块,执行完毕后
print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad)
print(f.name)
print('')

执行结果:

 执行enter
Traceback (most recent call last):
<__main__.Foo object at 0x01478A90>
File "D:/python/day28/s1.py", line 56, in <module>
执行exit
print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad) #触发__exit__
<class 'NameError'>
NameError: name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is not defined
name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is not defined
<traceback object at 0x01484710>

4、有返回值

如果__exit()返回值为True,那么异常会被清空,就好像啥都没发生一样,with后的语句正常执行

 class Foo:
def __init__(self,name):
self.name=name def __enter__(self):
print('执行enter')
return self
'''class、异常值、追踪信息'''
def __exit__(self, exc_type, exc_val, exc_tb): #2、有异常的时候,就会触发__exit__方法
print('执行exit')
print(exc_type)
print(exc_val)
print(exc_tb)
return True #3、没有return True就会报错,如果有return True异常自己吃了,不报异常 with Foo('a.txt') as f:
print(f)
print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad) #1、有异常的情况,他就会触发__exit__
print(f.name) #不执行这行,直接打印下面那行
print('') #4、最后打印这行

执行结果:

 执行enter
<__main__.Foo object at 0x016D8A90>
执行exit
<class 'NameError'>
name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is not defined
<traceback object at 0x016E5710>
000000000000000000000000000000000000000000000000000000

总结:

with obj as f:
      '代码块'

1.with obj ---->触发obj.__enter__(),拿到返回值

2.as f----->f=返回值、

3.with obj as f 等同于 f=obj.__enter__()

4.执行代码块
一:没有异常的情况下,整个代码块运行完毕后去触发__exit__,它的三个参数都为None
二:有异常的情况下,从异常出现的位置直接触发__exit__
a:如果__exit__的返回值为True,代表吞掉了异常
b:如果__exit__的返回值不为True,代表吐出了异常
c:__exit__的的运行完毕就代表了整个with语句的执行完毕

用途:

1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预

2.在需要管理一些资源比如文件,网络连接(TCP协议建连接、传输数据、关连接)和锁(进程,线程)的编程环境中,可以在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处。

十九、类的装饰器

示例1:类的装饰器基本原理

 #示例1
def deco(func): #高阶函数
print('===================')
return func #fuc=test @deco #装饰器 test=deco(test)
def test():
print('test函数运行')
test() #运行test

执行结果:

 ===================
test函数运行

示例2:类的装饰器基本原理

 def deco(obj):
print('============',obj)
obj.x=1 #增加属性
obj.y=2
obj.z=3
return obj @deco #Foo=deco(Foo) #@deco语法糖的基本原理(语法糖可以在函数前面加,也可以在类的前面加)
class Foo: #类的装饰器
pass print(Foo.__dict__) #加到属性字典中

执行结果:

 ============ <class '__main__.Foo'>
{'__module__': '__main__', 'z': 3, 'x': 1, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, 'y': 2}

用法总结:@deco语法糖可以在函数前面加,也可以在类的前面加

示例3:一切皆对象

 def deco(obj):
print('==========',obj)
obj.x=1
obj.y=2
obj.z=3
return obj # @deco #Foo=deco(test)
def test():
print('test函数')
test.x=1 #但没有人会这么做,只是验证一切皆对象
test.y=1
print(test.__dict__)

执行结果:

 {'x': 1, 'y': 1}

示例4:直接传值并加到字典中

 1 def Typed(**kwargs): #负责接收参数
2 def deco(obj): #局部作用域
3 obj.x=1
4 obj.y=2
5 obj.z=3
6 return obj
7 print('====>',kwargs) #外层传了个字典进来,就是: 'y': 2, 'x': 1,
8 return deco
9
10 @Typed(x=1,y=2,z=3) #typed(x=1,y=2,z=3)--->deco 函数名加()就是运行Typed函数
11 class Foo:
12 pass

执行结果:

 ====> {'y': 2, 'x': 1, 'z': 3}

示例5:类的装饰器增强版

 def Typed(**kwargs):  #Type传过来的参数,就是name='egon',kwargs包含的就是一个字典
def deco(obj):
for key,val in kwargs.items(): #key=name,val=age
setattr(obj,key,val) #obj=类名,key=name,val=age
return obj #返回类本身:obj,就相当于给类加了个属性
return deco @Typed(x=1,y=2,z=3) #1、typed(x=1,y=2,z=3)--->deco 2、@deco--->Foo=deco(Foo)
class Foo:
pass
print(Foo.__dict__) @Typed(name='egon') #@deco---->Bar=deco(Bar),重新赋值给了Bar
class Bar:
pass
print(Bar.name) #最后打印name,就得到egon

执行结果:

 {'y': 2, '__dict__': <attribute '__dict__' of 'Foo' objects>, 'z': 3, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__', 'x': 1, '__doc__': None}

 egon

实现:类型检测控制传入的值是什么类型

1、用raise抛出异常的方式实现

2、用类加装饰器实现 (这种方法更高级

示例6:类加装饰器的应用

示例如下:

1、给类加装饰器,实现控制传入的类型(推荐写法)  可以参考:  示例:4:用raise抛出异常的方式,判断传入的值是什么类型,同时可以判断多个属性。

 #给类加装饰器,实现控制传入的类型

 class Typed:
def __init__(self,key,expected_type):
self.key=key
self.expected_type=expected_type def __get__(self, instance, owner):
print('get方法')
return instance.__dict__[self.key] def __set__(self, instance, value):
print('set方法')
if not isinstance(value,self.expected_type):
raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
instance.__dict__[self.key]=value def __delete__(self, instance):
print('delete方法')
instance.__dict__.pop(self.key) def deco(**kwargs): #kwargs={'name':str,'age':int}
def wrapper(obj): #obj=People
for key,val in kwargs.items(): #(('name',str),('age',int))
# print(obj,key)
setattr(obj,key,Typed(key,val)) #给People设置类属性
return obj
return wrapper #给类加装饰器,加了装饰器,指定了什么类型,就必须传入什么类型的值,否则就会报错
@deco(name=str,age=int,salary=float) #@wrapper ===>People=wrapper(People) #实现这个功能的重点在这里
class People:
# name=Typed('name',int)
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary #name=srt,age=int,salary=float
#传入的是正确的类型,所以不会报错。
p1 = People('alex', 13, 13.3)
print(People.__dict__) #age设置成了int型,我们传入的是字符串类型,所以会报错:TypeError: age 传入的类型不是<class 'int'>
# p1=People('alex','13',13.3)
# print(People.__dict__)

执行结果:

 #传入正确类型的值

 set方法
set方法
set方法
{'__doc__': None, 'name': <__main__.Typed object at 0x010E3290>, '__dict__': <attribute '__dict__' of 'People' objects>, '__module__': '__main__', '__init__': <function People.__init__ at 0x010EB228>, 'salary': <__main__.Typed object at 0x010E3270>, '__weakref__': <attribute '__weakref__' of 'People' objects>, 'age': <__main__.Typed object at 0x010E32B0>} #传入错误类型的值,会报错,并提示你传入值的类型。

示例7:利用描述自定制property

 class Lazyproperty:
def __init__(self,func):
print('===========>',func)
self.func=func
def __get__(self,instance,owner):
print('get')
print('instance')
print('owner')
res=self.func(instance)
return res
class Room:
def __init__(self,name,width,length):
self.name=name
self.width=width
self.length=length
@Lazyproperty
def area(self):
return self.width * self.length r1=Room('厕所',1,1)
print(r1.area)

执行结果:

 get
instance
owner
1

示例8:利用描述符实现延迟计算

 class Lazyproperty:
def __init__(self,func):
print('===========>',func)
self.func=func
def __get__(self,instance,owner):
print('get')
print('instance')
print('owner')
res=self.func(instance)
return res
class Room:
def __init__(self,name,width,length):
self.name=name
self.width=width
self.length=length
@Lazyproperty
def area(self):
return self.width * self.length r1=Room('厕所',1,1)
print(r1.area)

示例9:非数据描述符

 class Lazyproperty:
def __init__(self,func):
self.func=func def __get__(self, instance, owner):
print('get') if instance is None:
return self
res=self.func(instance)
setattr(instance,self.func.__name__,res)
return res class Room:
def __init__(self,name,width,length):
self.name=name
self.width=width
self.length=length @Lazyproperty
def area(self):
return self.width * self.length
@property
def areal(self):
return self.width * self.length r1=Room('厕所',1,1) print(r1.area)
print(r1.__dict__) print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)

执行结果:

 get
1
{'area': 1, 'length': 1, 'name': '厕所', 'width': 1}
1
1
1
1
1
1
1
1

二十、元类(metaclass)

1、示例:

1 class Foo:
2 pass
3
4 f1=Foo() #f1是通过Foo类实例化的对象

python中一切皆是对象,类本身也是一个对象,当使用关键字class的时候,python解释器在加载class的时候就会创建一个对象(这里的对象指的是类而非类的实例)

上例可以看出f1是由Foo这个类产生的对象,而Foo本身也是对象,那它又是由哪个类产生的呢?

 class Foo:
pass f1=Foo() print(type(f1)) #<class '__main__.Foo'>
print(type(Foo)) #类的类就是<class 'type'> class Bar:
pass
print(type(Bar)) #<class 'type'>

执行结果:

 #type函数可以查看类型,也可以用来查看对象的类,二者是一样的。
<class '__main__.Foo'>
<class 'type'>
<class 'type'>

2、什么是元类?

元类是类的类,是类的模板

元类是用来控制如何创建类的,正如类是创建对象的模板一样

元类的实例为类,正如类的实例为对象(f1对象是Foo类的一个实例Foo类是 type 类的一个实例)

type是python的一个内建元类,用来直接控制生成类,python中任何class定义的类其实都是type类实例化的对象

3、创建类的两种方式

方式一:

 class Foo:
pass
print(Foo)
print(Foo.__dict__)

执行结果:

 <class '__main__.Foo'>
{'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>}

方式二:

 #type就是类的类,用type()实例化的结果,就是产生一个类
#用type和class生成的类是一样的效果。 def __init__(self,name,age):
self.name=name
self.age=age def test(self):
print('=======执行的是test=====>') FFo=type('FFo',(object,),{'x':1,'__init__':__init__,'test':test})
print(FFo)
# print(FFo.__dict__) f1=FFo('alex',18)
print(f1.x) #调的是类属性
print(f1.name) #调name
f1.test() #调方法

执行结果:

 <class '__main__.FFo'>
1
alex
=======执行的是test=====>

4、一个类没有声明自己的元类,默认他的元类就是type,除了使用元类type,用户也可以通过继承type来自定义元类。

示例:  自定制元类

 class MyType(type):
def __init__(self,a,b,c):
print('元类的构造函数执行') def __call__(self, *args, **kwargs):
obj=object.__new__(self) #object.__new__(Foo)-->f1
self.__init__(obj,*args,**kwargs) #Foo.__init__(f1,*arg,**kwargs)
return obj class Foo(metaclass=MyType): #Foo=MyType(Foo,'Foo',(),{})---》__init__
def __init__(self,name):
self.name=name #f1.name=name
f1=Foo('alex')

执行结果:

 元类的构造函数执行

python基础-面向对象进阶的更多相关文章

  1. python基础——面向对象进阶下

    python基础--面向对象进阶下 1 __setitem__,__getitem,__delitem__ 把对象操作属性模拟成字典的格式 想对比__getattr__(), __setattr__( ...

  2. python基础——面向对象进阶

    python基础--面向对象进阶 1.isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 ...

  3. python基础——面向对象编程

    python基础——面向对象编程 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的 ...

  4. python基础——面向对象的程序设计

    python基础--面向对象的程序设计 1 什么是面向对象的程序设计 面向过程的程序设计的核心是过程,过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西. 优 ...

  5. Python基础与进阶

    1 Python基础与进阶 欢迎来到Python世界 搭建编程环境 变量 | 字符串 | 注释 | 错误消除 他只用一张图,就把Python中的列表拿下了! 使用 If 语句进行条件测试 使用字典更准 ...

  6. Python 3 面向对象进阶

    Python 3 面向对象进阶 一.    isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的 ...

  7. Python 基础 面向对象之二 三大特性

    Python 基础 面向对象之二 三大特性 上一篇主要介绍了Python中,面向对象的类和对象的定义及实例的简单应用,本篇继续接着上篇来谈,在这一篇中我们重点要谈及的内容有:Python 类的成员.成 ...

  8. python基础--面向对象基础(类与对象、对象之间的交互和组合、面向对象的命名空间、面向对象的三大特性等)

    python基础--面向对象 (1)面向过程VS面向对象 面向过程的程序设计的核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西. ...

  9. Python基础—面向对象(进阶篇)

    通过上一篇博客我们已经对面向对象有所了解,下面我们先回顾一下上篇文章介绍的内容: 上篇博客地址:http://www.cnblogs.com/phennry/p/5606718.html 面向对象是一 ...

随机推荐

  1. Yii 2.x 日志记录器-类图

  2. PHPUnit整合ThinkPHP的库TPUnit

    项目地址:https://github.com/web3d/TPUnit ThinkPHP PHPUnit框架集成,基于TP3.2,建议PHP 5.4以上环境. 单元测试应该是提高PHP编码质量的解决 ...

  3. 一些简单的C语言算法

    1. 要求输入一个正整数,打印下述图形 输入:5 输出: * ** *** **** ***** 实现代码如下: #include <stdio.h> int main(int argc, ...

  4. 使用visualvm远程监控JVM LINUX服务器配置方法

    (1)首先要修改JDK中JMX服务的配置文件,以获得相应的权限: 进入$JAVA_HOME所在的根目录的/jre/lib/management子目录下, a. 将jmxremote.password. ...

  5. (转) Qt 出现“undefined reference to `vtable for”原因总结

    由于Qt本身实现的机制所限,我们在使用Qt制作某些软件程序的时候,会遇到各种各样这样那样的问题,而且很多是很难,或者根本找不到原因的,即使解决了问题,如果有人问你为什么,你只能回答--不知道. 今天我 ...

  6. Dynamics CRM 2015-如何修改Optionset Default Value

    在日常工作中,我们时不时会遇到在CRM测试环境上添加Optionset的时候,Default Value是某个值,但换到Production环境或者其他环境,添加的时候,Default Value可能 ...

  7. Atitit mac os 版本 新特性 attilax大总结

    Atitit mac os 版本 新特性 attilax大总结 1. Macos概述1 2. 早期2 2.1. Macintosh OS (系统 1.0)  1984年2 2.2. Mac OS 7. ...

  8. android okvolley框架搭建

    最近新出了很多好东西都没时间去好好看看,现在得好好复习下了,记下笔记 记得以前用的框架是android-async-http,volley啊,或者其它的,然后后面接着又出了okhttp,retrofi ...

  9. iOS调试通过UILocalNotification或RemoteNotification启动的app

    相信很多同学都为调试苹果的通知烦恼过,特别是通过通知启动app这个功能,简直让人欲哭无泪!!! 然而我们都遇到的问题,苹果怎么可能没有想到,原来早就有了官方的解决办法,只是我们不知道而已... 这次又 ...

  10. A new comer playing with Raspberry Pi 3B

    there are some things to do for raspberry pi 3b for the first time: 1, connect pi with monitor/KB/mo ...