2019年9月1日 定制format, slots 属性,doc属性
x='{0}{0}{0}'.format('a') print(x) class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day d1=Date(2099,1,2) y='{0.year}{0.mon}{0.day}'.format(d1) z='{0.year}-{0.mon}-{0.day}'.format(d1) print(y) print(z)
>>>>
aaa
209912
2099-1-2
format_dic={ 'ymd':"{0.year}:{0.mon}:{0.day}", 'm-d-y':'{0.mon}-{0.day}-{0.year}', } class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def __format__(self, format_spec): print('format 执行') if not format_spec or format_spec not in format_dic: #如果 format_spec为空,或者不在字典的格式内 format_spec='ymd' fm=format_dic[format_spec]#通过字典来进行选择 return fm.format(self) d1=Date(2099,1,2) zz=format(d1,'ymd') ww=format(d1,'m-d-y') print(zz) print(ww)
》》》》
format 执行
format 执行
2099:1:2
1-2-2099
**********
slots 属性:主要用来省内存
是一个类变量,变量的值可以是列表,元祖或者可迭代对象,也可以是字符串
使用点来访问属性本质是在访问类或者对象的__dict__属性字典
class Foo: __slots__ = ['name','age'] #相当于['name':None,'age':None] f1=Foo() f1.name='sxj' print(f1.name) f1.age='18' print(f1.age) # f1.gentle='man' #slots中没有定义 print(f1.__slots__)# 无__dict__了
》》》》
sxj
18
['name', 'age']
doc属性
无法继承
class Foo: '我是doc' pass class Bar(Foo): pass print(Bar.__dict__)#bar无法继承foo的doc print(Foo.__doc__)
>>>>
{'__module__': '__main__', '__doc__': None}
我是doc
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· Ollama本地部署大模型总结
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 在 VS Code 中,一键安装 MCP Server!
· 用一种新的分类方法梳理设计模式的脉络