如何创建接受多个参数的构造函数?

2024-07-05 11:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个特定的类,在设置__init__构造函数时遇到了困难。我需要它接受零个或多个字符串作为参数,每个字符串提供一个城市名称和州缩写,并指示美国城市旅游的目的地。你知道吗

例如:

Tour("New York, NY", "Lansing, MI", "Los Angeles, CA")

代表从纽约市开始,到兰辛,最后到洛杉矶的旅行。你知道吗

你知道如何使用Python3.3来实现这一点吗?你知道吗


Tags: 字符串名称new参数init代表cami
2条回答

This may help...

示例

class Bar:
   def __init__ (self, arg1=None, arg2=None, ... argN=None):

class NEW (Bar):    
    def __init__ (self, my_new_arg=None, ??? )
       self.new_arg = my_new_arg
       Bar.__init__(self, ??? )

像这样:

class Tour:
    def __init__(self, *cities):
        # cities is a tuple of arguments, do what you want with it

你知道吗

当你打电话的时候

Tour("New York, NY", "Lansing, MI", "Los Angeles, CA")

__init__中的cities将设置为("New York, NY", "Lansing, MI", "Los Angeles, CA")。你知道吗

相关问题 更多 >