__add__方法ide
#两个对象相加时,会自动执行第一个对象的__add__方法,而且将第二个对象当作参数传递进入 class foo: def __init__(self,name,age): self.name=name self.age=age def __add__(self, other): #return 123 #return self.age+other.age return foo("oo",20) # def __del__(self): # print("析构方法") obj1=foo("jiaxin",10) obj2=foo("lili",9) r=obj1+obj2 print(r,type(r)) # 123 <class 'int'> # 19 <class 'int'> # <__main__.foo object at 0x0000005CB825ABA8> <class '__main__.foo'> #__init__是建立对象时执行的函数,__del__在对象被销毁时自动触发执行的,叫析构方法
__dict__方法函数
#\__dict\__:经过字典的形式显示对象和类的成员 #显示对象成员 obj3=foo("zhangsan",60) d=obj3.__dict__ print(d) # {'name': 'zhangsan', 'age': 60} #显示类的成员 print(foo.__dict__) #查看类的成员 # {'__module__': '__main__', '__init__': <function foo.__init__ at 0x000000BAD00FD158>, '__add__': <function foo.__add__ at 0x000000BAD00FD1E0>, '__dict__': <attribute '__dict__' of 'foo' objects>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__doc__': None}
item方法code
#列表支持索引求职 list1=[1,2,3,4] r1=list1[2] list1[0]=5 list1[1:3:2] del list1[3] class foo1: def __init__(self,name,age): self.name=name self.age=age def __getitem__(self, item): if type(item)==slice: print("作切片处理") else: print("作索引处理") return item def __setitem__(self, key, value): print(key,value) def __delitem__(self, key): print(key) li=foo1("jia",30) r=li[88] #自动执行Li对象中的类的__getitem__方法,88当作参数传递给item #作索引处理 print(r) #切片取值和索引取值都执行getitem # 88 li[100]=123 # 100 123 print(li[100]) # 110 del li[999] # 999 print(li[7:20:2],type(li[5:8:2])) # 作切片处理 # 作切片处理 # slice(7, 20, 2) <class 'slice'>