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

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

问题描述

我找不到这个的确切答案。 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
pre>

你说什么?有更好的方法吗?

解决方案

实际上 None magicvalues:

  class Cheese():
def __init __(self,num_holes = None):
如果num_holes是无:
...

现在如果你想完全自由添加更多参数:

  class Cheese():
def __init __(self,* args,** kwargs):
#args - 匿名参数的元组
#kwargs - 命名参数的字典
self.num_holes = kwargs.get('num_holes',random_holes())

为了更好地解释 * args ** kwargs (你可以改变这些名字):

  def f ** 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


I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So what is a good way to solve this problem?

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

  • one that takes a number of holes like this: parmesan = Cheese(num_holes = 15)
  • and one that takes no arguments and just randomizes the number_of_holes property: gouda = Cheese()

I can think of only one way to do this, but that seems kinda 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 a better way?

解决方案

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

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

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