【发布时间】:2020-05-23 01:34:44
【问题描述】:
我正在尝试了解以下使用此类的一些代码结构:
class Base(object):
def __init__(self, **kwargs):
self.client = kwargs.get('client')
self.request = kwargs.get('request')
...
def to_dict(self):
data = dict()
for key in iter(self.__dict__): # <------------------------ this
if key in ('client', 'request'):
continue
value = self.__dict__[key]
if value is not None:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:
data[key] = value
return data
好的,我知道它获取传递给基类的键、值参数,例如Base(client="foo", request="bar")。
我的困惑是为什么它使用self.__dict__ 将__init__ 中的变量转换为字典(例如{"client": "foo", "request": "bar"}),而不是仅通过self.client 和self.request 在其他方法中调用它们,我在做什么错误的?何时以及为什么我应该改用self.__dict__?
请问我在哪里可以找到使用/理解这些笨方法的可靠指南?
提前谢谢你。
【问题讨论】:
标签: python class dictionary oop