0

以下:

class A(object):
    def __getattr__(self, attr):
        try:
            return self.__dict__[attr]
        except KeyError:
            self.__dict__[attr] = 'Attribute set to string'
            print 'Assigned attribute'
            return self.__dict__[attr]

返回:

obj = A()
obj.foo
Assigned attribute
Assigned attribute
Assigned attribute
'Attribute set to string'

魔法发生在哪里?

(我在 2.6.6)

编辑:感谢您的反馈。事实上,这个问题无法从 Python 命令行本身重现。似乎只有在 Eclipse/PyDev 中使用控制台时才会出现。

4

2 回答 2

3

我的代码版本略有不同,可能会有所帮助。

class A(object):
    def __getattr__(self, attr):
        try:
            return self.__dict__[attr]
        except KeyError:
            self.__dict__[attr] = 'Attribute set to string'
            print 'Assigned attribute', attr
            return self.__dict__[attr]

>>> o = A()
>>> o.foo
Assigned attribute foo
'Attribute set to string'

我不知道您如何多次看到“分配的属性”。这适用于 Python 2.6.6。

值得指出的是,如果调用try总是失败。__getattr__

于 2011-01-19T17:06:59.377 回答
1

这不会发生:

class A(object):
    def __getattr__(self, attr):
        try:
            return self.__dict__[attr]
        except KeyError:
            self.__dict__[attr] = 'Attribute set to string'
            print 'Assigned attribute'
            return self.__dict__[attr]

obj = A()
print obj.foo

给出:

Assigned attribute
Attribute set to string

__getattr__仅在属性不存在时调用!所以try .. except每次都会进入除...

它相当于:

class A(object):
    def __getattr__(self, attr):
        val = 'Attribute set to string'
        setattr(self, attr, val)
        print 'Assigned attribute'
        return val
于 2011-01-19T17:07:28.143 回答