python 之 面向對象(反射、__str__、__del__)

7.10 反射

下述四個函數是專門用來操作類與對象屬性的。通過字符串來操作類與對象的屬性,這種操作稱為反射

class People:
    country="China"
    def __init__(self,name):
        self.name=name
    def tell(self):
        print('%s is aaa' %self.name)
​
obj=People('egon')

hasattr:

print(hasattr(People,'country'))         #True
print('country' in People.__dict__)      #True
print(hasattr(obj,'name'))               #True
print(hasattr(obj,'country'))            #True
print(hasattr(obj,'tell'))               #True

getattr:

x=getattr(People,'country',None)
print(x)                        #China
​
f=getattr(obj,'tell',None)
print(f)            #<bound method People.tell of <__main__.People object at 0x000001E6AA9EACC0>>
print(obj.tell)      #<bound method People.tell of <__main__.People object at 0x000001E6AA9EACC0>>

setattr:

People.x=111
setattr(People,'x',111)
print(People.x)         #111
​
obj.age=18
setattr(obj,"age",18)
print(obj.__dict__)     #{'name': 'egon', 'age': 18}

delattr:

del People.country
delattr(People,"country")
print(People.__dict__)
​
del obj.name
delattr(obj,"name")
print(obj.__dict__)     # {'age': 18}

反射的應用:

class Foo:
    def run(self):
        while True:
            cmd=input('cmd>>: ').strip()    #用戶輸入的是字符串
            if hasattr(self,cmd):
                func=getattr(self,cmd)      #拿到函數地址
                func()
                
    def download(self):
        print('download....')
​
    def upload(self):
        print('upload...')
​
obj=Foo()
obj.run()

7.11__str__方法

__str__( )用於在對象print( )時自動觸發

class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
​
    def __str__(self):
        return '<名字:%s 年齡:%s 性別:%s>' %(self.name,self.age,self.sex)
​
obj=People('egon',18,'male')
print(obj)              # <名字:egon 年齡:18 性別:male>     # print(obj.__str__())
# l=list([1,2,3])
# print(l)

7.12 __del__方法

__del__( )用於在對象被刪除前,自動執行

class MyOpen:
    def __init__(self,filepath,mode="r",encoding="utf-8"):
        self.filepath=filepath
        self.mode=mode
        self.encoding=encoding
        self.fobj=open(filepath,mode=mode,encoding=encoding)    #申請系統資源
def __del__(self):      # 在回收程序空間(對象被刪除)前自動觸發__del__( ),刪除文件空間(系統空間)
        self.fobj.close()
f=MyOpen('aaa.py',mode='r',encoding='utf-8')     
res=f.fobj.read()
print(res)
点赞

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *