无法在Python中定义多个构造函数吗? [英] Is it not possible to define multiple constructors in Python?

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

问题描述

可能重复:
什么是干净,pythonic的方法在Python中有多个构造函数?

是否无法在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?

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

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

我想说 someCity = City() someCity = City("Berlin"),其中第一个只是给出默认名称值,第二个定义它.

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.

推荐答案

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

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天全站免登陆