gpt4 book ai didi

python - 自定义 __getattr__ 返回其他对象属性

转载 作者:行者123 更新时间:2023-12-01 09:17:48 26 4
gpt4 key购买 nike

import random

class Foo(object):
def __init__(self):
self._name = ''.join([chr(65 + random.randrange(0, 26)) for _ in range(3)])
self._data = None

def __getattr__(self, item):
dashitem = '_' + item
# if dhasattr(self, dashitem):
# is a bad idea because hasattr calls getattr
# is in self.__dict__.keys() also a bad idea?
if dashitem in self.__dict__.keys():
return self.__dict__[dashitem]

obj = Foo()
obj._data = [random.randrange(10, 100) for _ in range(random.randrange(1, 11))]

到目前为止,一切都很好。我可以调用obj.name and get back obj._name`

In [2]: obj.name
Out[2]: 'QZB'

In [3]: obj.data
Out[3]: [54]

然后我尝试酸洗该对象:

import pickle
pickle.dumps(obj)

但是这是不行的。

  File "<ipython-input-7-a7748eba906b>", line 2, in <module>
pickle.dumps(obj)
File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1380, in dumps
Pickler(file, protocol).dump(obj)
File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/Users/vishal/virtenvs/fm/bin/../lib/python2.7/copy_reg.py", line 84, in _reduce_ex
dict = getstate()

如何使用 __getattr__ 做我想做的事上面(如果在不破坏其他正常行为的情况下找不到 _<attr>,则返回 <attr>??

最佳答案

最简单的方法是简单地防止无限递归,并让默认逻辑处理其余的事情。重要的是不要隐式返回 None (在省略的 else-case 中这样做)并破坏默认行为(即当属性不存在时引发 AttributeError发现):

# ...
def __getattr__(self, item):
# all double-underscore attrs should be found before calling the fallback
if item.startswith('__'):
raise AttributeError
return getattr(self, '_'+item)

另请参阅this questiondocs .

关于python - 自定义 __getattr__ 返回其他对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51077889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com