Python的getattr行为?在ECLIPSE/PyDev控制台中?
以下是:Python的getattr行为?在ECLIPSE/PyDev控制台中?,python,pydev,getattr,Python,Pydev,Getattr,以下是: 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
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中使用控制台时才会发生这种情况。我有一个稍微不同的代码版本,可能会有所帮助
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'
我不知道你怎么会不止一次看到“指定属性”。这是在Python2.6.6中实现的
值得指出的是,如果调用了
\uu getattr\uuu
,则try
总是失败。我有一个稍微不同的代码版本,可能会有所帮助
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'
我不知道你怎么会不止一次看到“指定属性”。这是在Python2.6.6中实现的
值得指出的是,如果调用了\uu getattr\uuu
,则try
总是失败。这不会发生:
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
\uuuu getattr\uuuu
仅在属性不存在时调用!因此,尝试。。Exception
将在每次
这相当于:
class A(object):
def __getattr__(self, attr):
val = 'Attribute set to string'
setattr(self, attr, val)
print 'Assigned attribute'
return val
但事实并非如此:
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
\uuuu getattr\uuuu
仅在属性不存在时调用!因此,尝试。。Exception
将在每次
这相当于:
class A(object):
def __getattr__(self, attr):
val = 'Attribute set to string'
setattr(self, attr, val)
print 'Assigned attribute'
return val
对我来说,它只打印一次
Assigned属性
。尝试在def\uu getattr\uuuu行后打印“查找”,attr以查看需要的内容。好的,这很奇怪。它在Eclipse控制台中打印了三次,但使用命令shell中的解释器,它的行为是正确的。如果您可以复制它,请在a........dict..keys()]中对k执行smth操作,然后查看设置了哪些其他属性。然后你可以想一想原因。我在这里做一个粗略的猜测(我不使用eclipse),并说eclipse可能正在调用对象上的hasattr
,以完成代码,等等hasattr
是通过尝试getattr
来实现的。对我来说,它只打印分配的属性一次。我无法用python 2.5、2.6或3.1重现这一点。尝试在def\uu getattr\uuuu行后打印“查找”,attr以查看需要的内容。好的,这很奇怪。它在Eclipse控制台中打印了三次,但使用命令shell中的解释器,它的行为是正确的。如果您可以复制它,请在a........dict..keys()]中对k执行smth操作,然后查看设置了哪些其他属性。然后你可以想一想原因。我在这里做一个粗略的猜测(我不使用eclipse),并说eclipse可能正在调用对象上的hasattr
,以完成代码,等等hasattr
是通过尝试getattr
实现的。。。