当前位置 : 主页 > 编程语言 > python >

python 类特殊成员

来源:互联网 收集:自由互联 发布时间:2022-06-28
class Foo: def __init__(self,age): self.age=age print('init') def __call__(self): print('call') def __int__(self): return 123 def __str__(self): return 'foo' def __add__(self,other): return self.age+other.age def __del__(self):##gc回收foo销
class Foo:
def __init__(self,age):
self.age=age
print('init')
def __call__(self):
print('call')
def __int__(self):
return 123
def __str__(self):
return 'foo'
def __add__(self,other):
return self.age+other.age
def __del__(self):##gc回收foo销毁
print('foo is over')
def __getitem__(self,item):
return item+10
def __setitem__(self,key,value):
print(key,value)
def __delitem__(self,key):
print(key)


f=Foo(12)##调用init
f1=Foo(13)
f()##调用call
print(int(f))##调用int
print(f)##调用str
print(f+f1)##两个对象相加,会自动执行第一个对象的add方法 ,并且将第二个对象做为参数传递进去
print(f.__dict__ )#将对象的成员以字典类型全部显示 Foo.__dict__将类的所有成员和方法以字典类型显示
print(f[10])##调用getitem并将10传给item
f[10]=23#调用setitem将10传给10 23传给value
del f[10]##调用delitem

结果:

init
init
call
123
foo
25
{'age': 12}
20
(10, 23)
10

 


上一篇:python type metaclass
下一篇:没有了
网友评论