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

推荐订阅源

T
Tailwind CSS Blog
The GitHub Blog
The GitHub Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
量子位
Martin Fowler
Martin Fowler
月光博客
月光博客
P
Proofpoint News Feed
博客园_首页
Y
Y Combinator Blog
I
InfoQ
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Visual Studio Blog
H
Help Net Security
U
Unit 42
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - 西康的博客

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