码迷,mamicode.com
首页 > 编程语言 > 详细

python - 反射

时间:2018-04-23 01:28:40      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:error   obj   test   new   print   操作   class   通过   turn   

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

 

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

标签:error   obj   test   new   print   操作   class   通过   turn   

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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!