Day 22 __双下方法__
01 特殊方法
1,双下方法:
双下方法不是提供给你用的,他是给python源码的那些开发者用。
__len__ , __str__ , __call__ , __new__
# class A:
# def __init__(self,name,age):
# self.name = name
# self.age = age
# self.sex = '男'
# def __new__(cls, *args, **kwargs):
# print('in A __new__')
# return object.__new__(cls)
# def __len__(self):
# # print(666)
# return len(self.__dict__)
# def __str__(self):
# print(555)
# return 'fdsaf'
def __call__(self, *args, **kwargs):
# pass
a = A('addit',123) # 实例化
# len(a) # len(对象) 如果此类中有__len__ 就_方法会自动执行__len__
# print(a) # 对一个对象打印时,自动触发类中的__str__方法
# a() # 对象() 触发 __call__方法
2. isinstance , issubclass
isinstance 判断此对象是不是该类(或者是该类的子类)实例化的对象
print(isinstance(obj,B)) # True
issubclass 判断的是此类是不是后面类的派生类
print(issubclass(B,A)) # True
3.item 系列
item系列将对象视为字典使用时,就会触发item方法:
class Foo():
def __init__(self,name):
self.name = name
def __getitem__(self, item):
return self.name
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')
ret = f1['name']
print(ret)
f1['age'] = 12
4.反射
定义:通过字符串去操作对象(类,空间等等)的属性或方法
反射的四个方法:
hasattr(obj,str) ***
getattr(obj,str) ***
setattr(obj,str,str) *
delattr(obj,str) *
这里的obj只能是:实例化对象,类,其他py文件,本py文件
1)实例化对象
class A:
country = 'China'
area = '深圳'
def __init__(self,name,age):
self.name = name
self.age = age
def func(self):
print(666)
obj = A('addit',25)
if hasattr(obj,'name')
print(getattr(obj,'name')
ret = getattr(obj,'func')
print(ret) #<bound method A.func of <__main__.A object at 0x0000027608C674A8>>
2)操作类的角度
print(getattr(A,'country')) # china
print(getattr(A,'area')) # 深圳
print(getattr(A,'name)) # 报错
getattr(A,'func')(23) # 666
3)其他py文件的角度
attr模块
用反射的方法:
import attr
print(getattr(attr,'flag'))
1,找到func 并执行
ret = getattr(attr,'func')
print(ret(10))
2,找到B类并调用 name_list func函数
b = getattr(attr,'B')
print(b.name_list)
print(getattr(attr.B,'name_list'))
getattr(attr.B,'func')(1)
3,找到B类实例化对象在找 name,name_list func函数
b = getattr(attr,'B')
obj = b('alex','男')
print(obj.name)
print(obj.name_list)
4,本模块的反射
import sys
obj = sys.modules[__name__] # module '__main__'
print(obj)
def func():
print(666)
ret = input('>>>')
# ret()
getattr(obj,ret)()
def func1():
print('in func1')
def func2():
print('in func2')
def func3():
print('in func3')
l1 = [func1,func2,func3]
for i in l1:
i()
import sys
obj = sys.modules[__name__]
l1 = ['func%s' % i for i in range(1,4)]
print(l1)
for i in l1:
getattr(obj,i)()
到底什么对象才可以用反射?
# 实例化对象 类 其他模块 本模块 只有能通过.的方式获取的,才可以用反射。
5)区别本模块类与函数的调用
类:直接类.
# print(getattr(A,'country'))
setattr(obj,'func', func1)
函数:要通过找到本模块的py文件
# import sys
# obj = sys.modules[__name__]
# print(type(obj))
# # print(getattr(obj,'func'))

浙公网安备 33010602011771号