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

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: