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