在 Python 中拥有多个构造函数的干净的 Pythonic 方式是什么? [英] What is a clean, Pythonic way to have multiple constructors in Python?

查看:23
本文介绍了在 Python 中拥有多个构造函数的干净的 Pythonic 方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways of creating cheese objects...

  1. 一个有很多这样的洞:parmesan = Cheese(num_holes = 15)
  2. 还有一个不接受任何参数,只是随机化 number_of_holes 属性:gouda = Cheese()

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

I can think of only one way to do this, but this seems clunky:

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

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

What do you say? Is there another way?

推荐答案

实际上 None 对于魔法"值要好得多:

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

为了更好地解释*args**kwargs的概念(你实际上可以更改这些名称):

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

这篇关于在 Python 中拥有多个构造函数的干净的 Pythonic 方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆