python getattr和getattribute_getattr与getattribute的区别__

让我们看看__getattr__和__getattribute__魔术方法的一些简单示例。

__getattr__

每当您请求尚未定义的属性时,Python将调用__getattr__方法。在下面的示例中,我的类Count没有__getattr__方法。现在在main中,当我尝试同时访问obj1.mymin和obj1.mymax属性时,一切正常。但是当我试图访问obj1.mycurrent属性时——Python给了我AttributeError: 'Count' object has no attribute 'mycurrent'class Count():

def __init__(self,mymin,mymax):

self.mymin=mymin

self.mymax=mymax

obj1 = Count(1,10)

print(obj1.mymin)

print(obj1.mymax)

print(obj1.mycurrent) --> AttributeError: 'Count' object has no attribute 'mycurrent'

现在我的类Count有__getattr__方法。现在,当我尝试访问obj1.mycurrent属性时,python将返回我在__getattr__方法中实现的所有内容。在我的示例中,每当我试图调用一个不存在的属性时,python会创建该属性并将其设置为整数值0。class Count:

def __init__(self,mymin,mymax):

self.mymin=mymin

self.mymax=mymax

def __getattr__(self, item):

self.__dict__[item]=0

return 0

obj1 = Count(1,10)

print(obj1.mymin)

print(obj1.mymax)

print(obj1.mycurrent1)

__getattribute__

现在让我们看看__getattribute__方法。如果类中有__getattribute__方法,python将为每个属性调用此方法,而不管它是否存在。为什么我们需要__getattribute__方法?一个很好的原因是,您可以阻止对属性的访问,并使它们更安全,如下面的示例所示。

每当有人试图访问以substring开头的属性时,python就会引发AttributeError异常。否则它将返回该属性。class Count:

def __init__(self,mymin,mymax):

self.mymin=mymin

self.mymax=mymax

self.current=None

def __getattribute__(self, item):

if item.startswith('cur'):

raise AttributeError

return object.__getattribute__(self,item)

# or you can use ---return super().__getattribute__(item)

obj1 = Count(1,10)

print(obj1.mymin)

print(obj1.mymax)

print(obj1.current)

重要提示:为了避免__getattribute__方法中的无限递归,它的实现应该始终调用同名的基类方法来访问它需要的任何属性。例如:object.__getattribute__(self, name)或super().__getattribute__(item)而不是self.__dict__[item]

重要的

如果类同时包含getattr和getattribute魔术方法,则首先调用__getattribute__。但是如果__getattribute__升高

AttributeError异常然后将忽略该异常并调用__getattr__方法。请参见以下示例:class Count(object):

def __init__(self,mymin,mymax):

self.mymin=mymin

self.mymax=mymax

self.current=None

def __getattr__(self, item):

self.__dict__[item]=0

return 0

def __getattribute__(self, item):

if item.startswith('cur'):

raise AttributeError

return object.__getattribute__(self,item)

# or you can use ---return super().__getattribute__(item)

# note this class subclass object

obj1 = Count(1,10)

print(obj1.mymin)

print(obj1.mymax)

print(obj1.current)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值