[TOC]
1 setitem getitem delitem
把 对象操作属性模拟字典格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Foo: def __init__(self,name): self.name=name def __getitem__(self, item): return self.__dict__[item] def __setitem__(self, key, value): self.__dict__[key]=value def __delitem__(self,key): self.__dict__.pop(key) f=Foo('aaa') print(f['name']) f['age']=18 print(f.__dict__)
|
打印结果:
{‘name’: ‘aaa’, ‘age’: 18}
1 2 3 4 5 6
| f=Foo('aaa') print(f['name']) f['age']=18 del f['age'] del f['name'] print(f.__dict__)
|
结果:
2 __slots__
slots是一个类变量,变量的值可以是列表、字典、字符串、可迭代对象,用的是类的名称空间,是共享的,对象没有自己的名称空间,省内存
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class People: __slots__=['x','y','z'] p=People() print(People.__dict__) p.x=1 p.y=2 p.z=3 print(p.x,p.y,p.z) p1=People() p1.x=11 p1.y=21 p1.z=31 print(p1.x,p1.y,p1.z)
|
结果:
1 2 3
11 21 31
slots应用:字典会占用大量内存,如果一个类的属性很少,但是有很多类,为了节省内存可以使用slots代替dict
3 __next__和 __iter__实现迭代器协议
可迭代对象内置iter方法,可迭代对象赋值就是一个迭代器,迭代器可以使用next方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from collections import Iterator,Iterable class Foo: def __init__(self,start): self.start=start def __iter__(self): return self def __next__(self): if self.start > 10: raise StopIteration n = self.start self.start+=1 return n f=Foo(5) for i in f: print(i)
|
4 __doc__
1 2 3 4
| class Foo: '这是描述信息' pass print(Foo.__doc__)
|
无法继承
1 2 3 4 5 6
| class Foo: '这是描述信息' pass class Bar(Foo): pass print(Bar.__dic__)
|
结果:
type object ‘Bar’ has no attribute ‘dic‘
5 __module__和 class
module 表示当前操作的对象在那个模块
class 表示当前操作的对象的类是什么
1 2 3 4 5 6 7 8 9 10 11
| class Foo: '这是描述信息' pass class Bar(Foo): pass b=Bar() print(b.__module__) print(b.__class__) print(Bar.__class__) print(Foo.__class__)
|
结果:
main
class ‘main.Bar’>
class ‘type’>
class ‘type’>
加油