当前位置:
首页 > 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)
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式