Python随心记--类的内置attr属性

class Foo:
    x = 1
    def __init__(self,y):
        self.y = y
    def __getattr__(self, item):   #如果对象不存在的属性是会触发
        print('执行了__gerattr__')
    def __delattr__(self, item):   #删除的时候会触发
        print('执行了__delattr__')
        self.__dict__.pop(item)
    def __setattr__(self, key, value):   #设置属性是会触发,比如foo.x 当x不存在的时候就会触发__setattr__
        print('执行了__setattr__')
        #self.key = value   #不能致盲设置属性,会变成死循环(递归)
        self.__dict__[key] = value
foo = Foo(11)
print(dir(Foo))
组合的方式完成授权
import time
class FileHandle:
    def __init__(self,filename,mode='r',encoding='utf8'):
        # self.filename = filename
        self.file = open(filename,mode,encoding='utf8')
        self.mode = mode
        self.encoding = encoding

    def write(self,line):
        t = time.strftime('%Y-%m-%d %T')
        return self.file.write('%s %s' %(t,line))
    def __getattr__(self, item):
        # print('您请求的方法不存在')
        # self.file.read
        return getattr(self.file,item)   #返回self.file中的read方法

filehandle = FileHandle('a.txt','w+')
# print(filehandle.read)
filehandle.write('1111\n')
filehandle.write('2222\n')
filehandle.write('3333\n')

继承+派生完成包装
class List(list):
    def show_medllo(self):
        mid_index = int(len(self)/2);
        return self[mid_index]
    def append(self, p_object):
        if type(p_object) is str:
            # list.append(self,p_object)
            super().append(p_object)
        else:
           print('O(∩_∩)O,类型错了')
li = List('helloworld')


print(li.show_medllo())
li.append('720')
print(li)

issubclass() isinstance()
class Foo:
    pass
foo = Foo()
isinstance(foo,Foo)
issubclass(C,B)   #c类名雷曼B 判断c是否是继承B
__getattribute__
class Foo:
    def __init__(self,x):
        self.x = x
    def __getattr__(self, item):
        print('执行了__getattr__')
    def __getattribute__(self, item):   #属性有或者没有都出发她
        print('执行了__getattribute__')
        raise AttributeError('抛出异常了')
        # raise TabError('xxxxxxxxxxxxx')
foo = Foo(1)

foo.xxxx
item系列
class Foo:
    def __getitem__(self, item):
        print('getitem')
    def __setitem__(self, key, value):
        print('setitem')
    def __delitem__(self, key):
        print('delitem')

__str__ :自定义对象的显示方式
__repr__:自定义对象的显示方式

class Foo:
    def __str__(self):
        return '自定义对象的显示方式'
    def __repr__(self):
        return '自定义对象的显示方式1'

定制__format__
x = '{0}{0}{0}'.format('dog')
print(x)
format_dic={
    'ymd':'{0.year}{0.mon}{0.day}',
    'm-d-y':'{0.mon}-{0.day}-{0.year}',
    'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
    def __init__(self,year,mon,day):
        self.year=year
        self.mon=mon
        self.day=day
    def __format__(self, format_spec):
        print('我执行啦')
        print('--->',format_spec)
        if not format_spec or format_spec not in format_dic:
            format_spec='ymd'
        fm=format_dic[format_spec]
        return fm.format(self)
d1=Date(2016,12,26)
# format(d1) #d1.__format__()
# print(format(d1))
print(format(d1,'ymd'))
print(format(d1,'y:m:d'))
print(format(d1,'m-d-y'))
print(format(d1,'m-d:y'))
print('===========>',format(d1,'asdfasdfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasd'))
slots 属性 ,可节省内存(不推荐使用)
class Foo:
    __slots__ = ['name','age']   #实例化的对象不再有__dict__方法

f = Foo()
f.name = 'lin'
print(f.name)
__class__、__module__:查看对象来自那一模块

__del__:析构方法

__call__
class Foo:
    def __call__(self, *args, **kwargs):
        print('对象加小括号()也可以运行啦')
f = Foo()
f()
迭代器协议:

class Foo:
    def __init__(self,n):
        self.n = n
    def __iter__(self):   #加上后对象就可迭代 ,for循环
        pass

    def __next__(self):
        if self.n == 13:
            raise StopIteration('凉了')
        self.n += 1
        return self.n

f = Foo(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())

#斐那锲波
class Fib:
    def __init__(self):
        self._a = 1
        self._b = 1

    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 = Fib()
print(next(f))
print(next(f))

for i in f:
    print(i)

 

 
 
posted @ 2018-12-31 23:39  爱跑步的乌龟  阅读(592)  评论(0编辑  收藏  举报