python13-format和描述符

125 阅读1分钟

format

format_dic =  {
    'ymd':'{0.year}{0.mon}{0.day}',
    'y-m-d':'{0.year}-{0.mon}-{0.day}',
    'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date_Feng:
    def __init__(self,year,mon,day):
        self.year = year
        self.mon = mon
        self.day = day
    def __format__(self, format_spec):
        if not format_spec or format_spec not in format_dic:
            format_spec = 'ymd'
        fm = format_dic['y-m-d']
        return fm.format(self)
d1 = Date_Feng(2018,3,5)
print(format(d1,'y-m-d'))

slots

class Feng:
'我是一个类'
    #__slots__ = ['name','age']#{'name':None,'age':None}
    __slots__ = 'name'#{'name':None,'age':None}

f = Feng()
f.name  = 'fengfeng'
print(f.name)
#无法使用
#print(f.__dict__)
print(f.__slots__)
print(Feng.__slots__)
#打印描述信息,不能被继承
print(Feng.__doc__)

迭代器协议

# class Feng:
#     def __init__(self,n):
#         self.n = n
#     def __iter__(self):
#         return self
#     def __next__(self):
#         if self.n == 13:
#             raise StopIteration('停止了')
#         self.n = self.n + 1
#         return self.n
# # l = list('hello')
# # for i in l:
# #     print(i)
# f = Feng(0)
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# for i in f:
#     print(i)

class Feng:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __iter__(self):
        return self
    def __next__(self):
        if self.a > 100:
            raise  StopIteration("停止了")
        self.a,self.b = self.b,self.a +self.b
        return self.a

f = Feng(1,1)

print(next(f))
print(next(f))
print(next(f))
print(next(f))

描述符

class Feng:
    def __get__(self, instance, owner):
        print('get方法')
    def __set__(self, instance, value):
        print('set方法')
    def __delete__(self, instance):
        print('delete方法')
class Rong:
    x = Feng()

#实例 找不到属性 从类里面找,此时是Feng()
r = Rong()
# r.x = 10
# print(r.x)
# print(r.__dict__)#{}

#类属性
Rong.x = 1
print(Rong.__dict__)