python之路(10)类的内置函数
目录
- isinstance()和issubclass()
- __setitem__、__getitem__和__delitem__
- __str__和__reper__
- __format__
- __slots__
- __module__和__class__
- __del__
- __call__
- __iter__和__next__
isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls) 检查obj是否是cls的对象
issubclass(sub,super) 检查sub子类是否是super类的子类
__setitem__、__getitem__和__delitem__
class test: def __getitem__(self, item): print("getitem") return getattr(self,item) def __setitem__(self, key, value): print("setitem") setattr(self,key,value) #将值加到属性字典中 def __delitem__(self, key): print("delitem") delattr(self,key) t1 = test() #赋值 t1['name'] = 'chen' #setitem #取值 t1['name'] #getitem #删除 del t1['name'] #delitem
__str__和__repr__
__str__ 当print()输出实例时调用,类似java里的toString()方法
class test: def __str__(self): return "这里是__str__" t1 = test() print(t1) #这里是__str__
__repr__ 在pathon解释器中,直接打印实例对象触发。如果__str__没有定义时会调用__repr__,如果__str__有定义时会优先调用__str__
class test: # def __str__(self): # return "这里是__str__" def __repr__(self): return "这里是__repr__" t1 = test() print(t1) #这里是__repr__
__format__
__format__ 字符串格式化输出 format() 时调用
#自定制格式化输出 format_dict={ 'ymd':'{0.year}{0.mon}{0.day}', 'y-m-d':'{0.year}-{0.mon}-{0.day}', 'y:m:d':'{0.year}:{0.mon}:{0.day}' } class test: def __init__(self,year,mon,day): self.year = year self.mon = mon self.day = day def __format__(self, format_spec): #format()---->__format__() if not format_spec: format_spec = 'ymd' return format_dict[format_spec].format(self) t1 = test(2018,11,30) print(format(t1)) #20181130 print(format(t1, "y-m-d")) #2018-11-30 print(format(t1, "y:m:d")) #2018:11:30
__stols__
在通过类生成实例对象,每个实例都会生成一个独立的属性字典,为了节省内存空间,定义__stols__方法取代__dict__进行统一管理,作为一个内存优化工具
限制属性的创建,只能创建__stols__提供的属性
class test: __slots__ = ['name'] t1 = test() #由这个类产生的类不再具有__dict__属性字典 t1.name = 'chen' print(t1.name) #chen print(t1.__slots__ ) #['name'] print(t1.__dict__ ) # AttributeError: 'test' object has no attribute '__dict__' #限制属性的创建 t1.age = 18 #AttributeError: 'test' object has no attribute 'age'
__module__和__class__
__module__ 返回实例的模块
__class__ 返回实例的类
__del__(析构函数)
__del__ 实例对象被删除,系统回收内存时调用
__call__
实例对象加括号这样的形式调用,会执行__call__方法
注:类生成实例对象本质也是调用call方法
class test: def __call__(self, *args, **kwargs): print("call方法") t1 = test() t1() #call方法
__iter__和__next__
迭代器协议的两个内置方法
class test: def __init__(self,n): self.n=n def __iter__(self): return self def __next__(self): if self.n == 13: raise StopIteration('终止了') #迭代器抛出异常停止迭代 self.n += 1 return self.n t1 = test(10) #for循环会捕捉StopIteration异常,停止循环 for i in t1: #f1.__iter__ print(i)