1 class Foo: 2 '我是文档注释' 3 __slots__ = ['name','age'] #也可以是元组或者字符串 4 __slots__ = 'name' 5 #优点省内存,不必每个实例都单独弄一个字典,缺点,缺少了其他的属性,无法继承等等,可以用来限制用户添加多余的属性,但是核心本质还是节省内存 6 f1 = Foo() 7 f1.name = 'stt' #stt 8 f1.age = 18 #18 9 print(f1.name,f1.age,sep='\n') 10 f1.gender = 'male' #报错,不允许再添加除了__slots__列表或者元祖中的属性 11 12 # __doc__ 13 print(Foo.__doc__) #打印文档注释 我是文档注释 14 15 # __module__,__class__ 16 from test27 import Ttest 17 f1 = Ttest() 18 print(f1.name) 19 print(f1.__module__) #查看来自哪一个模块儿 test27 20 print(f1.__class__) #查看来自哪一个类 <class 'test27.Ttest'> 21 22 # __del__ 23 class Foo: 24 def __init__(self,name): 25 self.name = name 26 def __del__(self): #整个实例删掉的时候才会触发 27 print('我执行了') #整个程序执行完毕后内存释放,会触发python的垃圾回收机制(相当于删掉了实例),就会触发__del__()??? 28 29 f1 = Foo('stt') 30 del f1.name #删除一个实例的属性的时候不会触发__del__() 31 print('------------>') 32 # ------------> 33 # 我执行了 34 del f1 35 print('------------>') 36 # 我执行了 37 # ------------> 38 print(f1.name) #name 'f1' is not defined 39 40 class Foo: 41 pass 42 43 f1 = Foo() 44 f1.name = 'stt' 45 print(f1.name) 46 47 # __call__ 48 class Foo: 49 def __call__(self, *args, **kwargs): 50 print('call') 51 f1 = Foo() 52 f1() #call 53 # f1() 调用的是Foo下的__call__方法 54 # Foo() 调用的是xxx下的__call__方法,Foo实际上也是一个对象
__slots__,__doc__,__module__,__class__,__del__,__call__
猜你喜欢
转载自www.cnblogs.com/humanskin/p/9155065.html
今日推荐
周排行