item系列
通过点的方式对属性的操作触发的是attr内置函数
通过[ ]字典的操作触发的是item方法
__getitem__ __setitem__ __delitem__
f1[key]=value 可以触发__setitem__函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class yt():
yanzhi='meili'
def douzui(self):
print('哼,跟我争')
def __getitem__(self, item):
print('执行getitem')
# def __setitem__(self, key, value):
# print('执行setitem')
# def __delitem__(self, key):
# print('执行delitem')
y1=yt()
y1['douzui']
# print(y1.__dict__)
# y1.__dict__['shengao']='167'
# print(y1.__dict__)
# y1['shengao']
str和repr 改变对象的字符串显示
def __str__(self):
return "字符串" 必须return一个值(字符串),否则抛出异常
str(f1)——》f1.__str__()
repr在解释器触发
str和repr共存,调用str,找不到str就找repr
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class marry:
xintai='开心'
def tran(self):
print('去三亚')
# def __str__(self):
# return '123456'
# def __repr__(self):
# return '456'
c1=marry()
print(c1,type(c1))
# print(str(c1))
# print(c1.__str__())
# print(marry.__str__(c1))
format 自定制格式化方式format
slots属性
优势所在:省内存
劣势:其他属性用不了
慎用,挂钩的是对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class Foo: __slots__ = 'name' def bamei(self): print('你好') f1=Foo() f1.bamei() print(Foo.__dict__) f1.name=12 print(f1.name)