Python 如何访问类外的列表?

Python 如何访问类外的列表?,python,Python,因此,我用Place类生成了一堆地点,然后在Player类中,我尝试创建一个方法,通过我制作的向西旅行的地点列表查看当前位置和连接的位置,但是由于我是一个非常新的OOP,我不确定如何将Player函数的访问权授予main()中的列表 这也是在main()中生成播放器的地方: 以下是Place类构造函数: class Place(object): def __init__(self, name, weather, cl, pop, mayor): self.name = n

因此,我用Place类生成了一堆地点,然后在Player类中,我尝试创建一个方法,通过我制作的向西旅行的地点列表查看当前位置和连接的位置,但是由于我是一个非常新的OOP,我不确定如何将Player函数的访问权授予main()中的列表

这也是在main()中生成播放器的地方:

以下是Place类构造函数:

class Place(object):
    def __init__(self, name, weather, cl, pop, mayor):
        self.name = name
        self.weather = weather
        self.connectedLocation = cl
        self.population = pop
        self.mayor = mayor
class Player(object):
    def __init__(self, name, curLoc):
        self.name = name
        self.curLoc = curLoc
以下是播放器类构造函数:

class Place(object):
    def __init__(self, name, weather, cl, pop, mayor):
        self.name = name
        self.weather = weather
        self.connectedLocation = cl
        self.population = pop
        self.mayor = mayor
class Player(object):
    def __init__(self, name, curLoc):
        self.name = name
        self.curLoc = curLoc
后来在Player类中,我试图使此方法无效,因为令我沮丧的是,该类无法访问main()中的位置列表


您需要通过添加places参数将places列表传递给
goWest
函数。它看起来像这样:

def go_west(self, places):
    for place in places:
        if self.cur_loc.connected_location[0] == place.name:
            self.cur_loc = place
            break

我添加了break语句,因为我假设一旦找到当前位置,就不需要继续迭代列表。

天哪!我没想到这个解决方案会如此优雅,哎呀!我不知道方法的工作原理和函数一样。很高兴知道!非常感谢你!是的,OOP非常棒。另一个OOP小技巧是,不要在主方法中创建places数组,而是尝试将其添加为类级属性。然后,您可以将
self.places.append(self)
作为
Place
方法中的最后一行,以便通过OOP;)的强大功能填充数组。太神了我刚刚实现了它。它非常酷,您可以在init之前的Places类中创建一个列表,并且它再也不会使其为空。
def go_west(self, places):
    for place in places:
        if self.cur_loc.connected_location[0] == place.name:
            self.cur_loc = place
            break