1. 程式人生 > >Python隨心記--類的內建attr屬性

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)