Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的合成:获得上层阶级和上层阶级_Python_Python 3.x_Class - Fatal编程技术网

Python中的合成:获得上层阶级和上层阶级

Python中的合成:获得上层阶级和上层阶级,python,python-3.x,class,Python,Python 3.x,Class,我想通过写作从另一个类创建类 我以位于一个州的城市为例,该州本身属于一个国家。我想从我的国家班,能够添加国家,或从我的国家班添加城市,等等。。。因此,我编写了以下代码: from typing import Dict class City: def __init__(self, kwargs): self.name = kwargs['name'] class State: def __init__(self, kwargs): sel

我想通过写作从另一个类创建类

我以位于一个州的城市为例,该州本身属于一个国家。我想从我的国家班,能够添加国家,或从我的国家班添加城市,等等。。。因此,我编写了以下代码:

from typing import Dict


class City:

    def __init__(self, kwargs):
        self.name = kwargs['name']


class State:

    def __init__(self, kwargs):
        self.name = kwargs['name']
        self.cities = {}

    def add_city(self, name: str) -> None:
        kwargs = {'name': name}
        self.cities[name] = City(kwargs)

    def get_city(self, name: str) -> City:
        return self.cities[name]


class Country:

    def __init__(self, name):
        self.name = name
        self.states = {}

    def add_state(self, name: str) -> None:
        kwargs = {'name': name}
        self.states[name] = State(kwargs)

    def get_state(self, name: str) -> State:
        return self.states[name]
因此,我可以从我的国家班得到一个州,然后从我的国家班得到一个城市,等等。。。它很好用

usa = Country('USA')

usa.add_state('Texas')
texas = usa.get_state('Texas')

texas.add_city('Houston')
houston = texas.get_city('Houston')
print(houston.__dict__)
现在,我想从我的
houston
对象中获取生成该状态的state对象,然后是生成该状态的country对象。我该怎么做

理想情况下,我想要这样的东西:

houston.get_state().get_country()

请从下一页重复和。“为我设计此功能”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后就您的算法或技术提出具体问题。显而易见的方法是交叉引用所需的信息以便立即查找:同时向两个方向添加信息。存储数据库信息的方法有很多;这里的方法研究太广泛。在
add_state()
中添加类似于
self.states[name].country=self的内容来设置新创建的州的国家。类似于
add_city()
。是的,您需要编写此功能。将外接程序引用向后添加到类。这不是自动发生的。尽管也值得一提的是,您可能不希望重复引用。它产生了非常紧密的耦合,因为现在要把一个城市传递给一个功能,就必须传递整个国家和所有的东西(OOP的老话说,你想要一个香蕉,但你不小心让大猩猩拿着它和他的整个家庭)。让你的课程尽可能少,以后你会感谢你自己的。