当前位置: 移动技术网 > IT编程>软件设计>面向对象 > __getattribute__

__getattribute__

2019年06月09日  | 移动技术网IT编程  | 我要评论
[TOC] \_\_getattr\_\_ 不存在的属性访问,触发\_\_getattr\_\_ 10 执行的是我 \_\_getattribute\_\_ 查找属性无论是否存在,都会执行 你可真霸道呀!!! 不管是否存在,我都会执行 不管是否存在,我都会执行 \_\_getattr\_\_与\_\ ...

目录

__getattr__

  • 不存在的属性访问,触发__getattr__
class foo:
    def __init__(self, x):
        self.x = x

    def __getattr__(self, item):
        print('执行的是我')
        # return self.__dict__[item]


f1 = foo(10)
print(f1.x)
10
f1.xxxxxx
执行的是我

__getattribute__

  • 查找属性无论是否存在,都会执行

103-getattribute-霸道.jpg

  • 你可真霸道呀!!!
class foo:
    def __init__(self, x):
        self.x = x

    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')


f1 = foo(10)
f1.x
不管是否存在,我都会执行
f1.xxxxxx
不管是否存在,我都会执行

__getattr__与__getattribute__

  • 当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常attributeerror
#_*_coding:utf-8_*_
__author__ = 'linhaifeng'


class foo:
    def __init__(self, x):
        self.x = x

    def __getattr__(self, item):
        print('执行的是我')
        # return self.__dict__[item]
    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')
        raise attributeerror('哈哈')


f1 = foo(10)
f1.x
不管是否存在,我都会执行
执行的是我
f1.xxxxxx
不管是否存在,我都会执行
执行的是我

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网