What is a clean, pythonic way to have multiple constructors in Python?

后端 未结 13 2361
醉梦人生
醉梦人生 2020-11-22 07:12

I can\'t find a definitive answer for this. As far as I know, you can\'t have multiple __init__ functions in a Python class. So how do I solve this problem?

13条回答
  •  攒了一身酷
    2020-11-22 07:37

    Actually None is much better for "magic" values:

    class Cheese():
        def __init__(self, num_holes = None):
            if num_holes is None:
                ...
    

    Now if you want complete freedom of adding more parameters:

    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())
    

    To better explain the concept of *args and **kwargs (you can actually change these names):

    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

提交回复
热议问题