python中__getattribute__与__getattr__调用时的区别

"__getattribute__"方法小结:

     1. 任何调用类的属性行为都将从"__getattribute__"开始调用。

     2. 在"__getattribute__"中调用该函数自身属性,将会导致无限循环,应该借用object对象再调用其本身。所以如果要在自定义类中重写"__getattribute__"方法,首先该自定

         义类必须继承object对象,然后借用object对象再调用其本身返回属性值:  return object.__getattribute__(self, name),如果直接调用__getattribute__(self, name)则会

        无限递归

         以如下两个例子来说明:

          --------------------ex1:--------------------

          class User(object):       #   必须继承object

                    def __init__(self):

                           self.Id = 0                   

                     def def __getattribute__(self, name):
                           print  'get   '+name
                           return object.__getattribute__(self, name)      # 正常返回属性值    --借用object对象再调用其本身

 

           u=User()

           u.Id = 1

           print u.Id     

 

          ---------输出  

             'get  Id '

             '1'

 

          ----------------------------ex2:---------------------------

          class User(object):       #   必须继承object

                    def __init__(self):

                           self.Id = 0                   

                     def def __getattribute__(self, name):
                           print  'get   '+name
                           return self.__getattribute__(self, name)      #  陷入无限递归   

           u=User()

           u.Id = 1

           print u.Id     

 

          ---------输出  

             'get __getattribute__'

             'get __getattribute__'

             'get __getattribute__'

              'get __getattribute__'    . . .. . . . . . .. ..

 

 

 

"__getattr__"方法小结:

    1. "__getattr__"将会在寻找不到合适的函数或者属性时作为默认被调用到。

 

               class User(object):       #   必须继承object

                    def __init__(self):

                           self.Id = 0                   

                     def def __getattribute__(self, name):
                           print  'get   '+name
                           return object.__getattribute__(self, name)         

                    def def __getattr__(self, name):
                           print  'getattr  '+name
                           return self.__dict__.get(name)

           u=User()

           print u.Id2  

 

          ---------输出  

             'get  Id2'

             'getattr  Id2'

             None

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值