我有以下嵌套的字典:
world = {'europe' :
{'france' : ['paris', 'lion'],
'uk' : ['london', 'manchester']}},
{'asia' :
{'china' : ['beijing'],
{'japan' : ['tokyo']}}
我正在尝试以下对象:
class world:
continents = {} # dict of continents
class continent(world):
name = '' # name of the continent
countries = {} # dict of countries
class country(continent):
name = '' # name of the country
cities = [] # list of cities
class city(country):
name = '' # name of the city
目标是countries
从continent
对象中获取所有内容,或者从对象中获取country
和的continent
名称city
。
用Python做到这一点的最佳方法是什么?
从句法上讲,这些类应定义为
class World(object):
def __init__(self, continents):
self.continents = continents
class Continent(World):
def __init__(self, name):
self.name = '' # name of the continent
...
class Country(Continent):
def __init__(self, name):
self.name = '' # name of the country
...
class City(Country):
def __init__(self, name):
self.name = '' # name of the city
...
但是,在这种情况下,这没有任何意义。
子类化意味着其他:
Class Animal(object):
pass
Class Dog(Animal):
pass
Class Snake(Animal):
pass
狗是一种特殊的动物。狗是动物。蛇也是动物。
就您而言,大陆不是世界的类型,国家不是大陆的类型,依此类推。
相反,您想关联这些类,这些类可以作为单独的类存在,也可以在另一个内部使用。
例如
class City(object):
def __init__(self, name):
self.name = '' # name of the city
class Country(object, cities):
def __init__(self, name, cities):
self.name = name # name of the country
self.cities = cities # it's a list of Cities instances
class Continent(object):
def __init__(self, name, countries):
self.name = name # name of the continent
self.countries = countries # it's a list of Countries instances
class World(object):
def __init__(self, continents):
self.continents = continents # it's a list of Continent instances
france = Country('France', [City('Paris'), City('Annecy'), City('St. Tropez')])
italy = Country('Italy', [City('Rome'), City('Milan')])
uk = Country('UK', [City('London'), City('Bath')])
europe = Continent('europe', [france, italy, uk])
...
注意:以上仅是示例。由于多种原因,这可能不是在python中执行此操作的最佳方法,具体取决于您打算如何操作这些对象。
这是一个广泛而漫长的主题。
我建议在网上查找有关对象定向(也称为面向对象编程的OOP或面向对象设计的OOD)的良好教程。
这是一个教程,但是有成千上万的在线内容。
之后,您将能够设计对象应公开的接口,以便在本地/应用程序级别提供某些功能。
提示:使用RDBM(关系数据库管理系统)将帮助您关联和管理模型。了解有关ERD(实体关系图)的信息,以帮助您设计数据模型。
:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句