在Python中具有多个构造函数的一种干净的pythonic方法是什么?
【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>> 我找不到确切的答案。 据我所知,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 你说什么? 还有另一种方法吗? #1楼 我会使用继承。 尤其是如果差异大于孔数。 特别是如果Gouda将需要与Parmesan拥有不同的成员集。 class Gouda(Cheese): def __init__(self): super(Gouda).__init__(num_holes=10) class Parmesan(Cheese): def _