VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 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)


相关教程