1. 程式人生 > >python魔法函式之__getattr__與__getattribute__

python魔法函式之__getattr__與__getattribute__

getattr

在訪問物件的屬性不存在時,呼叫__getattr__,如果沒有定義該魔法函式會報錯

class Test:
    def __init__(self, name, age):
        self.name = name 
        self.age = age  
    
    def __getattr__(self, item):
        print(item)   // noattr
        return 'aa'


test = Test('rain', 25)
print(test.age)   // 25
print(test.noattr) //aa
getattribute

訪問物件任何屬性(即使屬性不存在)都會呼叫__getattribute__

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   04__getattr__與__getattribute__.py
@Time    :   2018/12/18 21:06:50
@Author  :   Rain 
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

# here put code


class Test:
    def __init__(self, name, age):
        self.name = name 
        self.age = age
    
    def __getattr__(self, item):
        print(item)
        return 'aa'

    def __getattribute__(self, item):  # 儘量不要使用它
        print('訪問屬性了')
        return 'bbb'

test = Test('rain', 25) 
print(test.age)
print(test.noattr)

結果: