私は次のネストされたdictを持っています:
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とも呼ばれます)に関する優れたチュートリアルをオンラインで探すことをお勧めします。
これが1つのチュートリアルですが、オンラインで利用できるものは数千あります。
その後、ローカル/アプリケーションレベルで特定の機能を提供するために、オブジェクトが公開する必要のあるインターフェイスを設計できるようになります。
ヒント:RDBM(リレーショナルデータベース管理システム)を使用すると、モデルの関連付けと管理に役立ちます。データモデルの設計に役立つERD(エンティティ関係図)について学習します。
:)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加