Python 默认情况下具有class属性的奇数getattr()行为
在这里,我希望所有4个ID都是相同的,但是,当我将class属性传递给Python 默认情况下具有class属性的奇数getattr()行为,python,python-3.x,getattr,Python,Python 3.x,Getattr,在这里,我希望所有4个ID都是相同的,但是,当我将class属性传递给getattr的default属性时,它只是跳过属性查找并始终返回default: Python 3.6.5 (default, May 11 2018, 04:00:52) Type 'copyright', 'credits' or 'license' for more information IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for he
getattr
的default
属性时,它只是跳过属性查找并始终返回default
:
Python 3.6.5 (default, May 11 2018, 04:00:52)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from datetime import datetime
...:
...: class my_cls(object):
...: @property
...: def _id(self):
...: self._cid = datetime.now().isoformat()
...: return self._cid
...:
...: def get_id(self):
...: return getattr(self, '_cid', self._id)
...:
...: cls = my_cls()
...: print('Init ID:', cls._id)
...: print('Still OK:', getattr(cls, '_cid', False))
...: print('WRONG:', getattr(cls, '_cid', cls._id))
...: print('WRONG:', cls.get_id())
...:
...:
Init ID: 2018-06-17T12:45:20.409601
Still OK: 2018-06-17T12:45:20.409601
WRONG: 2018-06-17T12:45:20.409804
WRONG: 2018-06-17T12:45:20.409849
这是预期的和/或记录的行为吗?为什么
getattr
在做它正在做的事情?它不是getattr
,而是你的代码在调用getattr
之前访问cls.\u id
在Python中,在调用函数之前,将计算其所有参数。特别是,在
getattr(cls,'.'u cid',cls.\u id)
子表达式cls.\u id
中进行计算。为此,访问\u id
属性,该属性将更新\u cid
getattr
之后被调用并返回更新的值。它不是getattr
,而是您的代码在调用getattr
之前访问cls.\u id
在Python中,在调用函数之前,将计算其所有参数。特别是,在
getattr(cls,'.'u cid',cls.\u id)
子表达式cls.\u id
中进行计算。为此,访问\u id
属性,该属性将更新\u cid
getattr
随后被调用并返回更新后的值。不生成具有副作用的属性,您就不会遇到此问题。不生成具有副作用的属性,您就不会遇到此问题。注意:您的报价getattr(cls,'.''.'''.''.'.\id)
不正确,应该是getattr(cls,'.'.\U cid',cls.\id)
@NarūnasK谢谢,修复。注意:您的报价getattr(cls,''u cid',cls.\u id)
不正确,应该是getattr(cls,''u cid',cls.\u id)
@NarūnasK谢谢,修复。