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

 

 

 

posted @ 2019-09-01 15:16  小圣庄  阅读(173)  评论(0编辑  收藏  举报