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

2024-05-29 00:01:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

假设我有一个名为Cheese的类,它具有number_of_holes属性。我怎么能有两种方法来创建奶酪对象。。。

  1. 一个有很多这样的洞的人:parmesan = Cheese(num_holes = 15)
  2. 一个不需要参数,只随机化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

你说什么?还有别的办法吗?


Tags: of对象方法函数答案number参数属性
3条回答

使用num_holes=None作为默认值是可以的,如果您只需要__init__

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

实际上,None对于“magic”值更好:

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

如果您想使用可选参数,所有这些答案都很好,但另一种可能是使用classmethod生成工厂风格的伪构造函数:

def __init__(self, num_holes):

  # do stuff with the number

@classmethod
def fromRandom(cls):

  return cls( # some-random-number )

相关问题 更多 >

    热门问题