Python之模块反射

Python之模块反射

#s2.py 模块s2
NAME = 'hongsong'

def func():
    return 'func'


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



#s1.py 模块s1
import s2

r1 = s2.NAME
print(r1)
r2 = s2.func()
print(r2)

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

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

输出:

hongsong
func
hongsong
<function func at 0x00000232D78BAD08>
func
<class 's2.Foo'>
123

猜你喜欢

转载自blog.csdn.net/hongsong673150343/article/details/88322399