python中的映射_一文读懂Python中的映射

python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

获取成员: getattrclass Foo:

def __init__(self, name, age):

self.name = name

self.age = age

obj = Foo('klvchen', 18)

inp = input('>>>')

v = getattr(obj, inp)

print(v)

运行结果:>>>name

klvchenclass Foo:

def __init__(self, name, age):

self.name = name

self.age = age

def show(self):

return "%s-%s" %(self.name, self.age)

obj = Foo('klvchen', 18)

func = getattr(obj, 'show')

print(func)

res = func()

print(res)

运行结果:>

klvchen-18

检查是否含有成员: hasattrclass Foo:

def __init__(self, name, age):

self.name = name

self.age = age

def show(self):

return "%s-%s" %(self.name, self.age)

obj = Foo('klvchen', 18)

print(hasattr(obj, 'name1'))

运行结果:False

设置成员: setattrclass Foo:

def __init__(self, name, age):

self.name = name

self.age = age

def show(self):

return "%s-%s" %(self.name, self.age)

obj = Foo('klvchen', 18)

# print(hasattr(obj, 'name1'))

setattr(obj, 'key', 'value')

print(obj.key)

运行结果:value

相关推荐:《Python相关教程》

删除成员: delattrclass Foo:

def __init__(self, name, age):

self.name = name

self.age = age

def show(self):

return "%s-%s" %(self.name, self.age)

obj = Foo('klvchen', 18)

print(obj.name)

delattr(obj, 'name')

print(obj.name)

运行结果:klvchen

AttributeError: 'Foo' object has no attribute 'name'

通过字符串的形式操作对象中的成员class Foo:

stat = '666'

def __init__(self, name, age):

self.name = name

self.age = age

res = getattr(Foo, 'stat')

print(res)

运行结果:666

创建两个文件,s1.py 和 s2.py

s2.py 内容如下:NAME = 'klvchen'

def func():

return 'func'

s1.py 内容如下:import s2

res1 = getattr(s2, 'NAME')

print(res1)

res2 = getattr(s2, 'func')

result = res2()

print(result)

运行 s1.py 文件:klvchen

func

创建两个文件,s1.py 和 s2.py

s2.py 内容如下:NAME = 'klvchen'

def func():

return 'cwe'

class Foo:

def __init__(self):

self.name = 666

s1.py 内容如下:import s2

res1 = getattr(s2, 'NAME')

print(res1)

res2 = getattr(s2, 'func')

result = res2()

print(result)

cls = getattr(s2, 'Foo')

print(cls)

obj = cls()

print(obj)

print(obj.name)

运行 s1.py 文件,运行结果:klvchen

cwe

666

创建两个文件,s1.py 和 s2.py

s2.py 内容如下:def f1():

return '首页'

def f2():

return '新闻'

def f3():

return '精华'

s1.py 内容如下:import s2

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

if hasattr(s2, inp):

func = getattr(s2, inp)

result = func()

print(result)

else:

print('404')

运行 s1.py 文件,运行结果:请输入要查看的URL: f1

首页

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值