一、反射概念

1、什么是反射?

指的是在程序运行过程中可以”动态(不见棺材不掉泪)”获取对象的信息

2、为何要用反射?

如何实现反射?
class People:
def init(self,name,age):
self.name=name
self.age=age

  1. def say(self):<br /> print('<%s:%s>' %(self.name,self.age))

obj=People(‘辣白菜同学’,18)

3、实现反射机制的步骤

1、先通过多dir:查看出某一个对象下可以.出哪些属性来
print(dir(obj))

2、可以通过字符串反射到真正的属性上,得到属性值
print(obj.dict[dir(obj)[-2]])

四个内置函数的使用:通过字符串来操作属性值
1、hasattr()
# print(hasattr(obj,’name’))
# print(hasattr(obj,’x’))

2、getattr()
# print(getattr(obj,’name’))

3、setattr()
# setattr(obj,’name’,’EGON’) # obj.name=’EGON’
# print(obj.name)

4、delattr()
# delattr(obj,’name’) # del obj.name
# print(obj.dict)

res1=getattr(obj,’say’) # obj.say
# res2=getattr(People,’say’) # People.say
# print(res1)
# print(res2)

obj=10
# if hasattr(obj,’x’):
# print(getattr(10,’x’))
# else:
# pass

print(getattr(obj,’x’,None))

if hasattr(obj,’x’):
# setattr(obj,’x’,111111111) # 10.x=11111
# else:
# pass

  1. class Ftp:
  2. def put(self):
  3. print('正在执行上传功能')
  4. def get(self):
  5. print('正在执行下载功能')
  6. def interactive(self):
  7. method=input(">>>: ").strip() # method='put'
  8. if hasattr(self,method):
  9. getattr(self,method)()
  10. else:
  11. print('输入的指令不存在')
  12. # obj=Ftp()
  13. # obj.interactive()

二、内置方法

1、什么是内置方法?


定义在类内部,以开头并以结果的方法
特点:会在某种情况下自动触发执行


2、为何要用内置方法?


为了定制化我们的类or对象


3、如何使用内置方法


str:在打印对象时会自动触发,然后将返回值(必须是字符串类型)当做本次打印的结果输出

  1. class People:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. def __str__(self):
  6. # print('运行了...')
  7. return "<%s:%s>" %(self.name,self.age)
  8. obj = People('辣白菜同学', 18)
  9. # print(obj.__str__())
  10. print(obj) # <'辣白菜同学':18>
  11. # obj1=int(10)
  12. # print(obj1)


del:在清理对象时触发,会先执行该方法
程序运行完也会触发

  1. class People:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. self.x = open('a.txt',mode='w')
  6. # self.x = 占据的是操作系统资源
  7. def __del__(self):
  8. # print('run...')
  9. # 发起系统调用,告诉操作系统回收相关的系统资源
  10. self.x.close()
  11. obj = People('辣白菜同学', 18)
  12. # del obj # obj.__del__()
  13. print('============>')

三、元类

1、引入:

一切都源自于一句话:一切皆为对象

2、什么是元类?

元类就是用来实例化产生类的类
关系:元类—-实例化——>类(People)—-实例化——>对象(obj)

class People:
def init(self,name,age):
self.name=name
self.age=age

  1. def say(self):<br /> print('%s:%s' %(self.name,self.name))

print(People.dict)
如何得到对象
obj=调用类()
obj=People(‘egon’,18)
print(type(obj))
如果说类也是对象
People=调用类(。。。)

查看内置的元类:
1、type是内置的元类
2、我们用class关键字定义的所有的类以及内置的类都是由元类type实例化产生
print(type(People))
print(type(int))

3、class关键字创造类People的步骤

类有三大特征:
1)类名
classname=”People”
2)类的基类
classbases=(object,)
3)执行类体代码拿到类的名称空间
class_dic={}
class_body=”””
def __init
(self,name,age):
self.name=name
self.age=age

def say(self):
print(‘%s:%s’ %(self.name,self.name))
“””
exec(class_body,{},class_dic)
# print(class_dic)

4)调用元类
People=type(class_name,class_bases,class_dic)

4、如何自定义元类来控制类的产生

class Mymeta(type): # 只有继承了type类的类才是元类
# 空对象,”People”,(),{…}
def init(self,x,y,z):
print(‘run22222222222….’)
print(self)
# print(x)
# print(y)
# print(z)
# print(y)
# if not x.istitle():
# raise NameError(‘类名的首字母必须大写啊!!!’)

  1. # 当前所在的类,调用类时所传入的参数<br /> def __new__(cls, *args, **kwargs):<br /> # 造Mymeta的对象<br /> print('run1111111111.....')<br /> # print(cls,args,kwargs)<br /> # return super().__new__(cls,*args, **kwargs)<br /> return type.__new__(cls,*args, **kwargs)

People=Mymeta(“People”,(object,),{…})
# 调用Mymeta发生三件事,调用Mymeta就是type.call
# 1、先造一个空对象=>People,调用Mymeta类内的new方法
# 2、调用Mymeta这个类内的init方法,完成初始化对象的操作
# 3、返回初始化好的对象

class People(metaclass=Mymeta):
def init(self,name,age):
self.name=name
self.age=age

  1. def say(self):<br /> print('%s:%s' %(self.name,self.name))

强调:
只要是调用类,那么会一次调用
1、类内的new
2、类内的init

5、call

  1. class Foo:
  2. def __init__(self,x,y):
  3. self.x=x
  4. self.y=y
  5. # obj,1,2,3,a=4,b=5,c=6
  6. def __call__(self,*args,**kwargs):
  7. print('===>',args,kwargs)
  8. return 123
  9. obj=Foo(111,222)
  10. # print(obj) # obj.__str__
  11. res=obj(1,2,3,a=4,b=5,c=6) # res=obj.__call__()
  12. print(res)

应用:如果想让一个对象可以加括号调用,需要在该对象的类中添加一个方法call
总结:
对象()->类内的call
类()->自定义元类内的call
自定义元类()->内置元类call

6、自定义元类控制类的调用=》类的对象的产生

class Mymeta(type): # 只有继承了type类的类才是元类
def call(self, args, **kwargs):
# 1、Mymeta.call函数内会先调用People内的new
peopleobj=self.new(self)
# 2、Mymeta.call函数内会调用People内的init
self._init
(people_obj,
args, **kwargs)

  1. # print('people对象的属性:',people_obj.__dict__)<br /> people_obj.__dict__['xxxxx']=11111<br /> # 3、Mymeta.__call__函数内会返回一个初始化好的对象<br /> return people_obj

类的产生
# People=Mymeta()=》type.call=>干了3件事
# 1、type.call函数内会先调用Mymeta内的new
# 2、type.call函数内会调用Mymeta内的init
# 3、type.call函数内会返回一个初始化好的对象

class People(metaclass=Mymeta):
def init(self,name,age):
self.name=name
self.age=age

  1. def say(self):<br /> print('%s:%s' %(self.name,self.name))
  2. def __new__(cls, *args, **kwargs):<br /> # 产生真正的对象<br /> return object.__new__(cls)

类的调用
# obj=People(‘egon’,18) =》Mymeta.call=》干了3件事
# 1、Mymeta.call函数内会先调用People内的new
# 2、Mymeta.call函数内会调用People内的init
# 3、Mymeta.call函数内会返回一个初始化好的对象

obj1=People(‘egon’,18)
obj2=People(‘egon’,18)
# print(obj)
print(obj1.dict)
print(obj2.dict)

四、属性查找

属性查找的原则:对象-》类-》父类
切记:父类 不是 元类

class Mymeta(type):
n=444

  1. def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'><br /> obj=self.__new__(self) # StanfordTeacher.__new__<br /> # obj=object.__new__(self)<br /> print(self.__new__ is object.__new__) #True<br /> self.__init__(obj,*args,**kwargs)<br /> return obj

class Bar(object):
# n=333

  1. # def __new__(cls, *args, **kwargs):<br /> # print('Bar.__new__')<br /> pass

class Foo(Bar):
# n=222

  1. # def __new__(cls, *args, **kwargs):<br /> # print('Foo.__new__')<br /> pass

class StanfordTeacher(Foo,metaclass=Mymeta):
# n=111

  1. def __init__(self,name,age):<br /> self.name=name<br /> self.age=age

obj=StanfordTeacher(‘lili’,18)
print(obj.dict)
# print(obj.n)
# print(StanfordTeacher.n)