这个问题已经有了答案:
在这里,我期望所有4个ID都是相同的,但是当我将类属性传递给 default 的属性 getattr ,它只跳过属性查找并始终返回 违约 以下内容:
default
getattr
违约
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 ,这是您的代码访问 cls._id 呼叫前 获取属性 .
cls._id
在python中,在调用函数之前,将计算其所有参数。尤其是在 getattr(cls, '_cid', cls._id) 子表达式 里昂证券 被评估。为了做到这一点, _id 属性被访问,更新 _cid . 获取属性 然后调用并返回更新的值。
getattr(cls, '_cid', cls._id)
里昂证券
_id
_cid