類的特殊成員
__add__方法
#兩個對象相加時,會自動執行第一個對象的__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方法
#列表支持索引求職
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'>