zoukankan      html  css  js  c++  java
  • python

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

    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')
  • 相关阅读:
    SVN服务器搭建和使用(一)
    Python3.x和Python2.x的区别
    myeclipse启动不了的解决方法
    学习第49天
    学习第48天
    学习第47天
    学习第46天
    学习第45天
    学习第44天
    学习第43天
  • 原文地址:https://www.cnblogs.com/qikang/p/8847390.html
Copyright © 2011-2022 走看看