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

发布于 2021-02-02 23:18:17

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

假设我有一个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

你说什么?还有另一种方法吗?

关注者
0
被浏览
71
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    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}
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看