在Python中有多个构造函数的干净,pythonic方法是什么?

我无法为此找到明确的答案。 AFAIK,在Python类中不能有多个__init__函数。 那么我该如何解决这个问题呢?

假设我有一个名为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())
    

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


    如果你只有__init__使用num_holes=None作为默认是好的。

    如果你想要多个独立的“构造函数”,你可以将它们作为类方法提供。 这些通常称为工厂方法。 在这种情况下,您可以将num_holes的默认值设置为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()
    

    如果您想使用可选参数,所有这些答案都非常出色,但另一种Pythonic可能性是使用classmethod来生成工厂样式的伪构造函数:

    def __init__(self, num_holes):
    
      # do stuff with the number
    
    @classmethod
    def fromRandom(cls):
    
      return cls( # some-random-number )
    
    链接地址: http://www.djcxy.com/p/26283.html

    上一篇: What is a clean, pythonic way to have multiple constructors in Python?

    下一篇: How to list all functions in a Python module?