python - 反射,,通过字符串的形式操作
python - 反射,,通过字符串的形式操作
通过字符串的形式操作对象的成员,叫做反射。
class Foo: def __init__(self,name,age): self.name = name self.age = age def show(self): return (‘{} - {}‘.format(self.name,self.age))obj = Foo(‘test_name‘,34)print (getattr(obj,‘name‘))print (hasattr(obj,‘age‘))setattr(obj,‘k1‘,‘v1‘)print (getattr(obj,‘k1‘))delattr(obj,‘age‘)print (getattr(obj,‘age‘))# test_name# print (getattr(obj,‘age‘))# True# AttributeError: ‘Foo‘ object has no attribute ‘age‘# v1
getattr
hasattr
setattr
delattr
class Foo: def index(self): return ‘index‘ def new(self): return (‘is new page‘) def test(self): return (‘is test page‘)f = Foo()while True: input_str = input(‘Please input URL: ‘) if input_str == ‘back‘ or input_str == ‘b‘: break if hasattr(f,input_str): get_func = getattr(f,input_str) print (get_func()) else: print (‘404 page‘)
python - 反射
相关内容
- [leetcode]Divide Two Integers @ Python,,原题地址:https
- python练习:字符串中的数字排序,,#字符串中的字数排
- Python-同时匹配邮箱和电话号码的正则表达式,,同时匹
- python3 aes加解密代码,,安装模块python
- 利用Python编写一个会员管理系统,沉迷于编程的世界里
- python查询MySQL数据库的表以及所有字段,,#!/usr/bin
- python-封装方法用于读取excel,,1.实现获取exce
- python字符串格式化方法%s和format函数,,1.%s方法一个例子
- python网络爬虫之使用scrapy自动登录网站,,前面曾经介绍
- Python判断一个字符串是否包含某个指定的字符串,,成员
评论关闭