首先先说两个模块,今天刚认识的两个内置函数:
isinstance:
判断一个变量是不是另一个变量的对象,对返回True,错Flase
class A: name='二狗' def __init__(self): pass b=3 a=A() print(isinstance(a,A)) print(isinstance(b,A))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
True
Process finished with exit code 0
issubclass:
判断类的关系,子父类,,对返回True,错Flase
class A: name='二狗' def __init__(self): pass class b(A): anme='打钩' def __init__(self): pass print(issubclass(b,A))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
True
Process finished with exit code 0
一,反射
其实说白了,反射就是用字符串类型的名字去操作变量
反射中主要要介绍的四种方法hasattr getattr setattr delattr
1,反射对象中的属性和方法:
class A: name='二狗' def func(self): print('你好') a=A() print(getattr(a,'name')) print(getattr(A,'name'))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
二狗
二狗
Process finished with exit code 0
class A: name='二狗' def func(self): print('你好') a=A() ret=getattr(a,'func') ret()
你好
Process finished with exit code 0
用类名调方法
class A: name='二狗' @classmethod def func(self): print('你好') a=A() ret=getattr(a,'func') ret() ret=getattr(A,'func') ret()
有的时候为了防止我们执行的变量函数里没有会报错,所以通常getattr会和hasattr合起来用
class A: name='二狗' @classmethod def func(self): print('你好') if hasattr(A,'fun'): ret=getattr(A,'fun') ret()
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
Process finished with exit code 0
有的时候用的用户交互,我们还可设置输入的什么,我们就可以直接调用:
class A: name='二狗' def func(self): print('你好') a=A() b=input('>>>>>>') print(getattr(a,b)) print(A.__dict__[b])
反射模块的属性
import mm print(mm.day) print(getattr(mm,'day'))
Monday
Monday
Process finished with exit code 0
反射内置模块
import time print(getattr(time,'time')()) print(getattr(time,'asctime')())
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe 1516607396.7829843 Mon Jan 22 15:49:56 2018 Process finished with exit code 0
反射自己模块中的变量
import sys def func(): print('你好') name='二狗' print(sys.modules['__main__'].name) print(getattr(sys.modules['__main__'],'name'))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
二狗
二狗
Process finished with exit code 0
调用自己模块中函数
import sys def func(): print('你好') name='二狗' print(getattr(sys.modules['__main__'],'func')())
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
你好
None
Process finished with exit code 0
__main__是写死的,有的时候我们可以是它灵活一点,把它换成__name__就好了
import sys,mm def func(): print('你好') name='二狗' getattr(sys.modules['__main__'],'func')() na=input('....') print(getattr(sys.modules[__name__],na))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
你好
....name
二狗
Process finished with exit code 0
如果函数有参数反射的话直接在后面加上就好了
import time print(time.strftime('%Y-%m-%d %H:%M:S')) print(getattr(time,'strftime')('%Y-%m-%d %H:%M:S') )
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe 2018-01-22 16:16:S 2018-01-22 16:16:S Process finished with exit code 0
反射一个模块中的类
import mm mm.C print(getattr(mm,'C'))
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe erha <class 'mm.C'> Process finished with exit code 0
setattr 设置修改变量
class A: name='二狗女' def func(self): print('不好') a=A() setattr(a,'name','大狗') print(a.name) print(A.name) print(getattr(a,'name')) print(getattr(A,'name')) setattr(A,'name','alex') print(A.name)
大狗
二狗女
大狗
二狗女
alex
delattr删除变量
class A: name='二狗女' def func(self): print('不好') a=A() setattr(a,'name','大狗') print(a.name) delattr(a,'name') print(a.name) delattr(A,'name') print(a.name)
大狗 Traceback (most recent call last): 二狗女 File "C:/s9/day27/fanshe", line 60, in <module> print(a.name) AttributeError: 'A' object has no attribute 'name' Process finished with exit code 1
二,,类的内置方法
__str__
__repr__
class Teacher: def __init__(self,name,salary): self.name = name self.salary = salary def __str__(self): return "Teacher's object :%s"%self.name def __repr__(self): return str(self.__dict__) def func(self): return 'wahaha' nezha = Teacher('哪吒',250) print(nezha) # 打印一个对象的时候,就是调用a.__str__ print(repr(nezha)) print('>>> %r'%nezha)
eacher's object :哪吒 {'name': '哪吒', 'salary': 250} >>> {'name': '哪吒', 'salary': 250} Process finished with exit code 0
# %s str() 直接打印 实际上都是走的__str__ # %r repr() 实际上都是走的__repr__ # repr 是str的备胎,但str不能做repr的备胎 # print(obj)/'%s'%obj/str(obj)的时候,实际上是内部调用了obj.__str__方法,如果str方法有,那么他返回的必定是一个字符串 # 如果没有__str__方法,会先找找父类中的__str__,再没有再本类中的__repr__方法
。 # repr(),只会找__repr__,如果没有找父类的
__len__
class Classes: def __init__(self,name): self.name = name self.student = [] def __len__(self): return len(self.student) def __str__(self): return 'classes' py_s9= Classes('python全栈9期') py_s9.student.append('二哥') py_s9.student.append('泰哥') print(len(py_s9)) print(py_s9)
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/Users/hc/AppData/Local/Temp/Rar$DIa4724.16488/3.类的内置方法.py 2 classes Process finished with exit code 0
__del__
析构方法,当对象在内存中被释放时,自动触发执行。
class Foo: def __del__(self): print('执行我啦') f1=Foo() del f1
:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
执行我啦
Process finished with exit code 0
__call__
对象后面加括号,触发执行。
class A: def __init__(self,name): self.name = name def __call__(self): for k in self.__dict__: print(k,self.__dict__[k]) a = A('alex')()
C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day27/fanshe
name alex
Process fini