python中有多个构造函数? [英] Multiple constructors in python?

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

问题描述


可能重复:


$$$$$$$$$$$$$$$

$$$$$$$$$$$$$$$$$$$



是否无法在Python中用不同的签名定义多个构造函数?如果不是,通常的解决方法是什么?



例如,假设您要定义一个 City



我想说 someCity = City() someCity = City( Berlin),第一个仅提供默认名称值,第二个定义默认值。

解决方案

与Java不同,您不能定义多个构造函数。但是,如果未传递默认值,则可以定义默认值。

  def __init __(self,city = Berlin): 
self.city =城市


Possible Duplicate:
What is a clean, pythonic way to have multiple constructors in Python?

Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it?

For example, let's say you wanted to define a class City

I'd like to be able to say someCity = City() or someCity = City("Berlin"), where the first just gives a default name value, and the second defines it.

解决方案

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city

这篇关于python中有多个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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