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

推荐订阅源

美团技术团队
N
Netflix TechBlog - Medium
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
博客园 - 【当耐特】
B
Blog
Stack Overflow Blog
Stack Overflow Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
博客园 - 司徒正美
博客园 - 叶小钗
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
酷 壳 – 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')