在Python中具有多个构造函数的一种干净的pythonic方法是什么?
我找不到确切的答案。据我所知,__init__Python
类中不能有多个功能。那么我该如何解决这个问题呢?
假设我有一个Cheese用number_of_holes
属性调用的类。我如何有两种创建奶酪对象的方式…
- 有很多这样的漏洞:
parmesan = Cheese(num_holes = 15)
- 还有一个不带参数而只是随机化
number_of_holes
属性的参数:gouda = Cheese()
我只能想到一种执行此操作的方法,但这似乎很笨拙:
class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
你说什么?还有另一种方法吗?
-
None
对于“魔术”值,实际上要好得多:class Cheese(): def __init__(self, num_holes = None): if num_holes is None: ...
现在,如果你想完全自由地添加更多参数:
class Cheese(): def __init__(self, *args, **kwargs): #args -- tuple of anonymous arguments #kwargs -- dictionary of named arguments self.num_holes = kwargs.get('num_holes',random_holes())
为了更好地解释
*argsand
的概念**kwargs
(你实际上可以更改这些名称):def f(*args, **kwargs): print 'args: ', args, ' kwargs: ', kwargs >>> f('a') args: ('a',) kwargs: {} >>> f(ar='a') args: () kwargs: {'ar': 'a'} >>> f(1,2,param=3) args: (1, 2) kwargs: {'param': 3}
-
num_holes=None
如果你将只需要使用default
作为默认值就可以了__init__
。如果需要多个独立的“构造函数”,则可以将它们作为类方法提供。这些通常称为工厂方法。在这种情况下,你可以有默认
num_holesBE 0
。class Cheese(object): def __init__(self, num_holes=0): "defaults to a solid cheese" self.number_of_holes = num_holes @classmethod def random(cls): return cls(randint(0, 100)) @classmethod def slightly_holey(cls): return cls(randint(0, 33)) @classmethod def very_holey(cls): return cls(randint(66, 100))
现在创建这样的对象:
gouda = Cheese() emmentaler = Cheese.random() leerdammer = Cheese.slightly_holey()