Maximum recursion depth error with getattr

谁说胖子不能爱 提交于 2019-12-20 04:26:24

问题


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?


回答1:


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]


来源:https://stackoverflow.com/questions/12163476/maximum-recursion-depth-error-with-getattr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!