[ python ] 反射

在python中,反射包含以下几个函数

复制代码
def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass
hasattr
复制代码
复制代码
def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass
getattr
复制代码
复制代码
def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass
setattr
复制代码
复制代码
def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
delattr
复制代码

 

 

hasattr  判断是否含有某属性

1
2
3
4
5
6
7
8
9
10
11
12
In [1]: class Person(object):
   ...:     def __init__(self, name, age):
   ...:         self.name = name
   ...:         self.age = age
 
In [2]: p = Person('hkey', 20# 实例化一个对象
 
In [3]: hasattr(p, 'name'# 通过 hasattr 判断 p 是否包含 name 属性,这里name参数必须是字符串类型
Out[3]: True
 
In [4]: hasattr(p, 'sex')   # 如果 p 中没有 sex 属性,则返回 False
Out[4]: False

 

getattr 获取对象的属性

 

1
2
3
4
5
6
7
8
9
10
11
12
13
In [5]: getattr(p, 'name'# p.name  =  getattr(p, 'name') 
Out[5]: 'hkey'
 
In [6]: getattr(p, 'age')   # p.age = getattr(p, 'age') 
Out[6]: 20
 
In [7]: getattr(p, 'sex')   # p.sex = getattr(p, 'sex') p 对象中不包含 sex 属性则报错.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-36d4b75cf6b8> in <module>
----> 1 getattr(p, 'sex')
 
AttributeError: 'Person' object has no attribute 'sex'

 

getattr 进阶用法:

当使用 getattr 获取不存在属性的时候,我们不希望直接抛出异常。

1
getattr(对象, 'str1', '对象属性不存在时的默认信息')

 

1
2
3
4
In [16]: getattr(p, 'sex', '不知道')   # p 对象中是没有 sex 属性,直接返回默认值
Out[16]: '不知道'
In [17]: getattr(p, 'sex', 'None'# 一般来说直接设置为 None
Out[17]: 'None'

 

setattr 设置对象的属性

 

1
2
3
4
In [8]: setattr(p, 'sex', 'male')   # 通过 setattr 为 p 对象设置为 sex 属性,属性值为 male
 
In [9]: p.sex   # 验证 setattr 是否设置成功
Out[9]: 'male'

 

setattr 进阶用法:

setattr 不仅可以为对象添加属性,还可以为对象绑定方法

1
2
3
4
In [23]: setattr(p, 'say_hello', lambda self: 'hello, ' + self.name)    # setattr(对象名, '方法名', '匿名函数') self 代表对象本身
 
In [24]: p.say_hello(p) # 调用方式必须将对象传入 对象.方法名(对象)
Out[24]: 'hello, hkey'

 

delattr 删除对象的属性

 

1
2
3
4
5
6
7
8
9
In [10]: delattr(p, 'sex'# 通过 delattr 删除 p 对象的 sex 属性
 
In [11]: p.sex  # 验证 sex 属性是否删除成功
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-0e282ee1b157> in <module>
----> 1 p.sex
 
AttributeError: 'Person' object has no attribute 'sex'

 

反射在实际代码中使用的非常普遍,尤其是在和用户交互的时候。

实例:自行编写一个shell,当要执行一个命令的时候使用反射来执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
 
 
class Manage_cmd(object):
    def run(self):
        while True:
            cmd = input('>>>').strip()
            if not cmd: continue
            if hasattr(self, cmd):  # 通过 hasattr 来判断对象self是否含有cmd属性
                getattr(self, cmd)()   
            else:
                print('-bash: %s: command not found' % cmd)
 
    def ls(self):
        print(os.listdir('.'))
 
    def exit(self):
        exit(1)
 
 
cmd = Manage_cmd()
cmd.run()

 

执行结果:

 

本文作者:hukey

本文链接:https://www.cnblogs.com/hukey/p/9964256.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   hukey  阅读(362)  评论(0编辑  收藏  举报
历史上的今天:
2016-11-15 [ 操作系统 ] 内存篇
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 彩虹 Jay
彩虹 - Jay
00:00 / 00:00
An audio error has occurred.

彩虹 + 轨迹 (Live) - 周杰伦 (Jay Chou)

彩虹

词:周杰伦

曲:周杰伦

哪里有彩虹告诉我

哪里有彩虹告诉我

能不能把我的愿望还给我

能不能把我的愿望还给我

为什么天这么安静

为什么天这么安静

所有的云都跑到我这里

有没有口罩一个给我

有没有口罩一个给我

释怀说了太多就成真不了

释怀说了太多就成真不了

也许时间是一种解药

也许时间是一种解药

也是我现在正服下的毒药

也是我现在正服下的毒药

看不见你的笑 我怎么睡得着

看不见你的笑 我怎么睡得着

你的声音这么近我却抱不到

你的声音这么近我却抱不到

没有地球太阳还是会绕

没有地球太阳还是会绕

没有理由我也能自己走

没有理由我也能自己走

你要离开 我知道很简单

你要离开 我知道很简单

你说依赖 是我们的阻碍

你说依赖 是我们的阻碍

就算放开 但能不能别没收我的爱

就算放开 但能不能别没收我的爱

当作我最后才明白

当作我最后才明白

看不见你的笑 要我怎么睡得着

看不见你的笑 要我怎么睡得着

你的声音这么近我却抱不到

没有地球太阳还是会绕 会绕

没有理由我也能自己走掉

释怀说了太多就成真不了

也许时间是一种解药 解药

也是我现在正服下的毒药

轨迹

词:黄俊郎

曲:周杰伦

我会发着呆然后忘记你

接着紧紧闭上眼

想着哪一天 会有人代替

想着哪一天 会有人代替

让我不再想念你

我会发着呆 然后微微笑

我会发着呆 然后微微笑

接着紧紧闭上眼

又想了一遍 你温柔的脸

又想了一遍 你温柔的脸

在我忘记之前