python之反射

class Foo:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show(self):
        return '%s---%s' % (self.name, self.age)

obj = Foo('alex', 18)
# 去什么东西里获取什么属性
# inp = input('>>>')
# ret = getattr(obj, inp)
# print(ret)
# >>>show
# >
# >>>name
# alex
func = getattr(obj, 'show')
print(func)
r = func()
print(r)
# >
# alex---18
# 检测obj里是否有'name'
print(hasattr(obj, 'name'))  # True
setattr(obj, 'k1', 'v1')
print(obj.k1)  # v1
delattr(obj, 'k1')
print(obj.k1)  # AttributeError: 'Foo' object has no attribute 'k1'

反射中的一些方法:getattr、setattr、hasattr、delattr,通过字符串的形式操作对象的成员。

 

在同一目录下建立s1.py   s2.py。

s2.py

NAME = 'alex'

def func():
    return 'func'


class Foo:
    def __init__(self):
        self.name = 123

s1.py

import s2
# r1 = s2.NAME
# r2 = s2.func()
# print(r1)
# print(r2)
# alex
# func

r1 = getattr(s2, 'NAME')
print(r1)
result = getattr(s2, 'func')
r2 = result()
print(r2)
# alex
# func

cls = getattr(s2, 'Foo')
print(cls)  # 
obj = cls()
print(obj.name)  # 123

举个例子

s1.py

import s2
inp = input('请输入要查看的URL:')

if hasattr(s2, inp):
    func = getattr(s2, inp)
    result = func()
    print(result)
else:
    print('404')

s2.py

def f1():
    return '首页'

def f2():
    return '新闻'

def f3():
    return '精华'

python之反射_第1张图片

 

你可能感兴趣的:(python编程)