Python中的getattr,__getattr__,__getattribute__和__get__详解

Python中的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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注云海天教程的更多内容!