我正在编写一个名为“Bag”的简单 Python 类:
class Bag:
def __init__(self, items=None):
if self.items == None:
self.items = defaultdict()
else:
temp_dict = defaultdict()
for key in self.items:
temp_dict[key] += 1
self.items = temp_dict
变量items接受一个对象列表,例如:
['d','a','b','d','c','b','d']
从那里,“def __init__(self, items=None)”将:
- 将items初始化为一个空的defaultdict,如果没有传递给items,或者
- 如果将对象列表传递到 items,则初始化传入的参数。
例如,这应该有效:
b = Bag()
没有参数应该没问题,因为 items 默认设置为 _None。
但是,这总是引发异常(来自检查错误的脚本):
*Error: b = Bag() raised exception AttributeError: 'Bag' object has no attribute 'items'
我想初始化 Bag() 而不向 items 传递参数。
希望一切都清楚,如果不是请告诉我。
有什么想法或代码有什么问题吗?
最佳答案
from collections import defaultdict
class Bag(object):
def __init__(self, items=None):
self.items = items or list()
if not self.items:
self.items = defaultdict()
else:
temp_dict = defaultdict()
for key in self.items:
temp_dict[key] += 1
self.items = temp_dict
我做了一些更正:
1) 创建 self.items
并用 items
初始化
2) 使用 is None
或简单地 not self.items
与 None 进行比较,因为空列表的计算结果为 False
关于python - 如何在 Python 中创建 "optional"参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554486/