首页 > 编程语言 > 详细

python - 反射

时间:2018-04-23 01:12:38      阅读:157      评论:0      收藏:0      [点我收藏+]

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

 

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 - 反射

原文:https://www.cnblogs.com/qikang/p/8847390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!