Python中的getattr,__getattr__,__getattribute__和__get__详解 目录 getattr __getattr__ getattribute get 总结 getattr getattr(object, name[, default])是Python的内置函数之一,它的作用是获取对象的属性. 示例 class Foo: ... def __init__(self, x): ... self.x = x ... f = Foo(10) getattr(f, 'x')
目录
- getattr
- __getattr__
- getattribute
- get
- 总结
getattr
getattr(object, name[, default])
是Python的内置函数之一,它的作用是获取对象的属性。
示例
>>> class Foo:
... def __init__(self, x):
... self.x = x
...
>>> f = Foo(10)
>>> getattr(f, 'x')
10
>>> f.x
10
>>> getattr(f, 'y', 'bar')
'bar'
__getattr__
object.__getattr__(self, name)
是一个对象方法,当找不到对象的属性时会调用这个方法。
示例
>>> class Frob:
... def __init__(self, bamf):
... self.bamf = bamf
... def __getattr__(self, name):
... return 'Frob does not have `{}` attribute.'.format(str(name))
...
>>> f = Frob("bamf")
>>> f.bar
'Frob does not have `bar` attribute.'
>>> f.bamf
'bamf'
getattribute
object.__getattribute__(self, name)
是一个对象方法,当访问某个对象的属性时,会无条件的调用这个方法。该方法应该返回属性值或者抛出AttributeError
异常。
示例
>>> class Frob(object):
... def __getattribute__(self, name):
... print "getting `{}`".format(str(name))
... return object.__getattribute__(self, name)
...
>>> f = Frob()
>>> f.bamf = 10
>>> f.bamf
getting `bamf`
10
get
__get__()
方法是描述器方法之一。描述器用于将访问对象属性转变成调用描述器方法。
示例
>>> class Descriptor(object):
... def __get__(self, obj, objtype):
... print("get value={}".format(self.val))
... return self.val
... def __set__(self, obj, val):
... print("set value={}".format(val))
... self.val = val
...
>>> class Student(object):
... age = Descriptor()
...
>>> s = Student()
>>> s.age = 12
set value=12
>>> print(s.age)
get value=12
12
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注我们的更多内容!
本文标题为:Python中的getattr,__getattr__,__getattribute__和__get__详解


基础教程推荐
- python验证多组数据之间有无显著差异 2023-08-08
- 使用Pycharm创建一个Django项目的超详细图文教程 2022-09-02
- linux 安装 python3 2023-09-03
- 云服务器Ubuntu更改默认python版本 2023-09-03
- Python+OpenCV实战之实现文档扫描 2022-10-20
- MySQL数据优化-多层索引 2023-08-11
- windows下面使用多版本Python安装指定版本的虚拟环境 2023-09-04
- 创建python虚拟环境(在ubuntu16.04中) 2023-09-04
- Python爬虫爬取属于自己的地铁线路图 2023-08-05
- 远程和Ubuntu服务器进行Socket通信,使用python和C#(准备篇) 2023-09-05