本文介绍了getattr的最大递归深度误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码;
class NumberDescriptor(object):
def __get __(self,instance,owner )
name =(hasattr(self,name)和self.name)
如果不是名字:
name = [attr for dir(owner)如果getattr(owner, attr)是自我] [0]
self.name = name
return getattr(instance,'_'+ name)
def __set __(self,instance,value):
name =(hasattr(self,name)和self.name)
如果不是名字:
owner = type(instance)
name = [attr for dir(owner)if getattr(owner,attr)is self] [$]
self.name = name
setattr(instance,'_'+ name,int(value))
class Insan (对象):
yas = NumberDescriptor()
a = Insan()
打印a.yas
a.yas =osman
打印我在线上获得最大的递归深度错误 name = [...] attr for attr in di r(owner)if getattr(owner,attr)is self] [0]
。我想要该行让我看到当前描述符实例使用的变量的名称。谁能看到我在这里做错什么?解决方案 getattr()
call调用你的 __ get __
。
解决这个问题的一种方法是明确地调用超类, 对象
:
object .__ getattribute __(instance,name)
或者,更清楚:
instance .__ dict __ [name]
I have this code;
class NumberDescriptor(object):
def __get__(self, instance, owner):
name = (hasattr(self, "name") and self.name)
if not name:
name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
self.name = name
return getattr(instance, '_' + name)
def __set__(self,instance, value):
name = (hasattr(self, "name") and self.name)
if not name:
owner = type(instance)
name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
self.name = name
setattr(instance, '_' + name, int(value))
class Insan(object):
yas = NumberDescriptor()
a = Insan()
print a.yas
a.yas = "osman"
print a.yas
I am getting maximum recursion depth error in the line name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
. I want that line to get me the name of variable used for current descriptor instance. Can anyone see what am I doing wrong here?
解决方案 The getattr()
call is calling your __get__
.
One way to work around this is to explicitly call through the superclass, object
:
object.__getattribute__(instance, name)
Or, clearer:
instance.__dict__[name]
这篇关于getattr的最大递归深度误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!