惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
爱范儿
爱范儿
罗磊的独立博客
美团技术团队
Jina AI
Jina AI
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
IT之家
IT之家
雷峰网
雷峰网
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
月光博客
月光博客
人人都是产品经理
人人都是产品经理
博客园 - 三生石上(FineUI控件)

博客园 - 西康的博客

mysql information_schema库中COLUMNS 和 TABLES表字段详解 python - queue 队列模块 python - 修改系统环境变量 python - threading 多进程模块 python - socketserver python - socket 基础 python 序列化 字典 异常处理 类的成员,类的特殊方法 elasticsearch RESTfull _cat api python - 面向对象编程基础知识 (进阶) python - 面向对象编程基础知识 python 文件操作 python re 模块 正则表达式 python configparser 模块 python logging 模块 python hashlib 模块 python sys 模块
python - 反射
西康的博客 · 2018-04-23 · via 博客园 - 西康的博客

通过字符串的形式操作对象的成员,叫做反射。

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')