代码之家  ›  专栏  ›  技术社区  ›  winsmith

在Python中使用多个构造函数的干净的Python方式是什么?

  •  594
  • winsmith  · 技术社区  · 17 年前

    我找不到一个明确的答案。据我所知,你不能有多个 __init__ Python类中的函数。那么我该如何解决这个问题呢?

    假设我有一个叫做 Cheese number_of_holes 所有物我怎样才能有两种方法来创建奶酪对象。。。

    1. 一个像这样的孔: parmesan = Cheese(num_holes = 15)
    2. 财产: gouda = Cheese()

    我只能想到一种方法,但这似乎很笨拙:

    class Cheese():
        def __init__(self, num_holes = 0):
            if (num_holes == 0):
                # Randomize number_of_holes
            else:
                number_of_holes = num_holes
    

    13 回复  |  直到 5 年前
        1
  •  5
  •   teichert    5 年前

    事实上 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())
    

    为了更好地解释 *args **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}
    

    http://docs.python.org/reference/expressions.html#calls