Python—面向对象05 反射
2024-10-09 01:25:40
反射,通过字符串映射到对象属性
class People:
country='China'
def __init__(self,name,age):
self.name=name
self.age=age
def talk(self):
print('%s is talking' %self.name)
p = People("gd", 22)
print(p.name) # p.__dic__['name']
print(p.talk) # <bound method People.talk of <__main__.People object at 0x00000000027B7470>>
print(hasattr(p, 'name')) # True 判断 对象p 里有没有 name 属性, hasattr(),第一个参数传对象,第二个参数传 属性名
print(hasattr(p, 'talk1')) # True
print(getattr(p, 'name')) # gd 拿到 对象 p 里的属性
# print(getattr(p, 'name2')) # AttributeError: 'People' object has no attribute 'name2'
# getattr(), 没有相应属性的时候,会报错,我们可以传入第三个参数
print(getattr(p, 'name2', None)) # None 这样,找不到属性的时候就会返回 None 了
setattr(p, 'sex', '机器大师')
print(p.sex) # 机器大师
print(p.__dict__) # {'name': 'gd', 'age': 22, 'sex': '机器大师'}
delattr(p, 'sex') # 删除属性
print(p.__dict__) # {'name': 'gd', 'age': 22}
# hasattr() getattr() setatter() delattr() 不仅适用于对象,也可以用于类
print(hasattr(People, 'country')) # True
print(getattr(People, 'country')) # China
反射的应用
class Service:
def run(self):
while True:
cmd = input(">>:").strip()
if hasattr(self, cmd):
func = getattr(self, cmd)
func()
def get(self):
print('get......')
def put(self):
print('put.....')
obj = Service()
obj.run()
# >>:get
# get......
# >>:put
# put.....
最新文章
- Python中的网络编程
- Silverlight动态生成控件实例
- Android深度探索--HAL与驱动开发----第五章读书笔记
- nba技能表
- Flipping elements with WPF
- BestCoder Round #74
- mysql概要(四)order by,group 的特点,子查询
- selenium+python自动化之操作浏览器
- ASP.NET FormsAuthentication跨站点登录时绝对地址返回的问题
- 另一种数据库连接字符串的编写方式(Sqlbuilder)
- 遗传算法Matlab源程序
- vhost:一种 virtio 高性能的后端驱动实现
- 安装SQL server 2008 R2和QL server 2008,与SQL server 2008升级SQL server 2008 R2
- day09--函数的定义分类以及其使用(1)
- 斯坦福大学公开课机器学习:advice for applying machine learning | model selection and training/validation/test sets(模型选择以及训练集、交叉验证集和测试集的概念)
- Bringing Native Performance to Electron
- Kafka命令行操作及常用API
- vue的组件之间传值方法
- 关于itext生成pdf的新的demo(包含简单的提取txt文件的内容 和xml内容转化为pdf)
- python之join