反射(重点)
hasattr,getsttr,setattr,delattr,其中(hasattr,getsttr成对出现,也是最重要的),(,setattr,delattr了解就行,没那么重要)
hasttr可以调用类中的@classmethod, @staticmethod方法,也可以调用类的实例化对象
class A: line = [1,2,3] def func(self): print('666') @classmethod def eat(cls): print('吃粑粑') a=A() if hasattr(a,'line'): print(getattr(a,'line')) #[1, 2, 3] ret = getattr(a,'func') ret() #666 if hasattr(A,'eat'): rep = getattr(A,'eat') rep() #吃粑粑
反射当前模块
import sys def func(): print('666') year = 2019 print(getattr(sys.modules[__name__],'year')) #2019 getattr(sys.modules['__main__'],'func')() #666
导入其他模块,利用反射查找该模块是否存在某个方法
import time print(time.strftime('%Y-%m-%d %X')) time.sleep(1) print(getattr(time,'strftime')('%Y-%m-%d %X'))
__str__和__repr__
自我感觉__str__和 __repr__没多大的区别,只是__repr__ 在python解析器里面不用输出就可以打印返回值
class Student: def __init__(self,name,salary): self.name = name self.salaey =salary def __str__(self): return self.name a=Student('小明',6000) print(a) #小明
__repr__
class Student: def __init__(self,name,salary): self.name = name self.salary =salary def __repr__(self): return self.name a=Student('小明','6000') print(a) #小明
剩余的可以查看Q1mi博客(地址:http://www.cnblogs.com/Eva-J/articles/7351812.html)