简体   繁体   English

Python __getattr__行为? 在ECLIPSE / PyDev控制台中?

[英]Python __getattr__ behavior? IN ECLIPSE/PyDev console?

The following: 下列:

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]

returns: 收益:

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

Where is the magic happening? 魔术在哪里发生?

(I'm on 2.6.6) (我在2.6.6上)

Edit : Thanks for your feedback. 编辑 :感谢您的反馈。 Indeed, this problem can't be reproduced from the Python command line itself. 确实,这个问题不能从Python命令行本身重现。 It seems that it only occurs when using the console in Eclipse/PyDev. 似乎仅在Eclipse / PyDev中使用控制台时才会发生。

I have a slightly different version of your code that might help. 我的代码版本稍有不同,可能会有所帮助。

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'

I don't know how you see "Assigned attribute" more than once though. 我不知道您如何多次看到“分配的属性”。 This is with Python 2.6.6. 这是Python 2.6.6。

It's worth pointing out that the try always fails if __getattr__ is called. 值得指出的是,如果调用__getattr__ ,则try总是失败。

That doesn't happen: 那不会发生:

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

gives: 得到:

Assigned attribute
Attribute set to string

__getattr__ is only called when the attribute does not exist! 仅当属性不存在时才调用__getattr__ So the try .. except will go into the except every time ... 所以每次try .. except都会进入除外...

It's equivalent to: 等效于:

class A(object):
    def __getattr__(self, attr):
        val = 'Attribute set to string'
        setattr(self, attr, val)
        print 'Assigned attribute'
        return val

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM