问题描述
$$$$$$$$$$$$$$$ $$$$
$$$$$$$$$$$$$$$$$$$
是否无法在Python中用不同的签名定义多个构造函数?如果不是,通常的解决方法是什么?
例如,假设您要定义一个 City $ c $类c>
我想说 someCity = City()
或 someCity = City( Berlin)
,第一个仅提供默认名称值,第二个定义默认值。
与Java不同,您不能定义多个构造函数。但是,如果未传递默认值,则可以定义默认值。
def __init __(self,city = Berlin):
self.city =城市
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中有多个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!