【Python学習の旅】---継承方式完成包装(ライセンス、itemシリーズ、str&repr、formatカスタムフォーマット方法)

8398 ワード

# 、         

class List(list): # list
def append(self,name):
if type(name) is str: # ,
super().append(name) #

def show_middle(self):
middle=int(len(self)/2) #
return self[middle] #


l1=List('chenyuxia')
print(l1)
l1.append('sb') #
print(l1) #
print(l1.show_middle()) #

# :


# :

['c', 'h', 'e', 'n', 'y', 'u', 'x', 'i', 'a']['c', 'h', 'e', 'n', 'y', 'u', 'x', 'i', 'a', 'sb']u
 
#二、組み合わせの方式で授権を完成する
#ライセンスはパッケージの一種であり、上書き_getaddr__実現する
import time
class FileHandle:
def __init__(self,filename,mode='r',encoding='utf-8'):
# self.filename=filename
self.file=open(filename,mode,encoding=encoding) # ,
self.mode=mode
self.encoding=encoding
def write(self,line):
print('------------>',line)
t=time.strftime('%Y-%m-%d %X') #
self.file.write('%s %s' %(t,line)) #

def __getattr__(self, item):
# print(item,type(item))
# self.file.read
return getattr(self.file,item)

f1=FileHandle('a.txt','w+')
#print(f1.file)
#print(f1.__dict__)
#print('==>',f1.read) # __getattr__, self.file
#print(f1.write) # __getattr__, self.file
f1.write('1111111111111111
')
f1.write('cpu
')
f1.write('
')
f1.write('
')
f1.seek(0)
print('--->',f1.read())

# :

------------> 1111111111111111
--------->cpu負荷が高すぎる
--------->メモリ不足
--------->ハードディスクの残量不足
----->2020-01-06 21:02:01 11111111111111112020-01-06 21:02:01 cpu負荷過高2020-01-06 21:02:01メモリ残不足2020-01-06 21:02:01ハードディスク残不足
 
三、itemシリーズの方法
#              
class Name:
def __getitem__(self, item):
print('getitem',item)
return self.__dict__[item]
def __setitem__(self, key, value):
print('setitem')
self.__dict__[key]=value

def __delitem__(self, key):
print('delitem')
self.__dict__.pop(key)

n1=Name()
n1['name']='chenyuxia'
n1['age']=18
print(n1.__dict__)
del n1['age']
print(n1.__dict__)

print(n1['name'])

# :

setitemsetitem{'name': 'chenyuxia', 'age': 18}delitem{'name': 'chenyuxia'}getitem namechenyuxia
 
四、strとrepr方法
#                 ,  return     
# str
class Foo:
def __init__(self,name,age):
self.name=name
self.age=age

def __str__(self): # F1 ,prtint
return ' str'

def __repr__(self): #
return ' %s, %s ' % (self.name, self.age)



F1=Foo('chenyuxia',18)

print(F1) #str(F1)-->F1.__str()-->F1.__repr__() , str, repr

# :
str


、 format
dic={
'ymd':'{0.year} {0.mon} {0.day}',
'd-m-y':'{0.year}-{0.mon}-{0.day}',
'y:m:d':'{0.year}:{0.mon}:{0.day}'
}

class Foo:
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 dic: # ,
format_spec='ymd' #
fm=dic[format_spec] # ,
return fm.format(self) #

f1=Foo(2016,1,4)
print(format(f1,'55555')) # self format_spec


# :
2016 1 4