日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python基础第19天

發布時間:2025/5/22 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础第19天 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?面向對象基礎講解二

一:雙下劃線開頭的attr方法

  • __getattr__() ?只有屬性不存在時,會觸發
  • __setattr__() ?設置屬性時,會觸發
  • __delattr__() ?刪除屬性時會觸發
class Foo:x=1def __init__(self,y):self.y=y #__getattr__()def __getattr__(self, item):print('執行__getattr__')f1=Foo(10) #f1就是self print(f1.y) print(getattr(f1,'y')) f1.sssssssssssssssss #不存在時觸發class Foo:x=1def __init__(self,y):self.y=y #__delattr__()def __delattr__(self, item):print('執行__delattr__')f1=Foo(10) del f1.y del f1.x


class Foo:x=1def __init__(self,y):self.y=ydef __setattr__(self,key,value): #__setattr__()print('執行__setattr__')# self.key=value #無限遞歸self.__dict__[key]=valuef1=Foo(10) print(f1.__dict__) f1.z=2 print(f1.__dict__)


class Foo:def __init__(self,name):self.name=name #只要是這種形式的就會觸發__setattr__def __getattr__(self, item):print('你找到屬性【%s】不存在'%item)def __setattr__(self, k, v):print('執行__setattr__',k,v)if type(v)is str:print('開始設置')self.__dict__[k]=velse:print('必須是字符串類型')def __delattr__(self, item):print('執行delattr',item)self.__dict__.pop(item)f1=Foo('alex') print(f1.name) print(f1.age) print(f1.__dict__) f1.age=18 #會觸發__setattr---- f1.gender='male' print(f1.__dict__) del f1.name print(f1.__dict__)#執行__setattr__ name alex #開始設置 #alex #你找到屬性【age】不存在 #None #{'name': 'alex'} #執行__setattr__ age 18 #必須是字符串類型 #執行__setattr__ gender male #開始設置 #{'name': 'alex', 'gender': 'male'} #執行delattr name #{'gender': 'male'}

二:授權(包裝的特性)

? ? ? 所有更新的功能都是由新類的某部分來處理,但是已存在的功能就授權給對象的默認參數。

? ? ? 實現授權的關鍵點就是覆蓋__getattr__方法。

import time class Open:def __init__(self,filename,mode='r',encoding='utf-8'):# self.filename=filenameself.file=open(filename,mode,encoding=encoding) #封裝了文件操作的方法(繼承)self.mode=modeself.encoding=encodingdef write(self,line):t=time.strftime('%Y-%m-%d %X')self.file.write('%s %s'%(t,line))def __getattr__(self, item):# print(item,type(item))return getattr(self.file,item) #通過字符串找到自己屬性 # # # f1=Open('a.txt','w') print(f1.file) print('--->',f1.read)# sys_f=open('b.txt','w+') # print(getattr(sys_f,'read'))print(f1.write) f1.write('1234\n') #2017-03-13 09:11:03 1234 # f1.seek(0) #
f1.write(
'cpu負載過高\n')
f1.write(
'內存剩余不足\n')
f1.write(
'硬盤剩余不足\n')
# 2017-03-13 09:14:29 cpu負載過高
2017-03-13 09:14:29 內存剩余不足
2017-03-13 09:14:29 硬盤剩余不足

? ? ?例子核心點是:利用getattr通過字符串找到自己屬性,通過返回給self.file擁有文件操作的功能。

?

轉載于:https://www.cnblogs.com/xyd134/p/6540134.html

總結

以上是生活随笔為你收集整理的Python基础第19天的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。