Art*_*art 1 python string class instance python-2.6
我正在为一个学校项目制作一个程序.这是模拟联合国.
countries = ['Australia', 'Brazil', 'Canada']
class delegate(object):
   def __init__(self, country):
     self.country = country
我有一个国家列表和一个名为delegate的类.因此,每个委托对象必须有一个国家/地区.通常我会这样做:
mexico = delegate('Mexico')
就是这样.但我想循环遍历国家/地区列表并为每个列表创建类实例.我的意思是:
australia = delegate('Australia')
brazil = delegate('Brazil')
canada = delegate('Canada')
等等. 我该怎么做? 非常感谢你!!
从列表创建命名变量通常是个坏主意.也许你可以试试
countries = ['Australia', 'Brazil', 'Canada']
class Delegate(object):    # according to PEP8, class names should be title-case
    def __init__(self, country):
        self.country = country
# create a dict
delegates = {country: Delegate(country) for country in countries}
编辑:根据@SethMMorton,Python 2.6不理解字典理解(即我上面使用的).您可以使用获得相同的结果
delegates = dict([(country, Delegate(country)) for country in countries])