所以我用Place类生成了一堆地方,然后在Player类中我尝试制作一个查看当前位置的方法,并通过我向西行进的地点列表查看连接的位置,但是我是非常新的OOP我不知道如何将访问Player函数的权限授予main()中的列表
def main():
import random
places = []
places.append(Place("Boston", "Sunny - 55°F", ("Worcester", None), "645,966", "Marty Walsh"))
places.append(Place("Worcester", "Sunny - 64°F", ("Springfield", "Boston"), "182,544", "Joseph Petty"))
places.append(Place("Springfield", "Sunny - 67°F", ("Pittsfield", "Worcester"), "153,703", "Domenic Sarno"))
places.append(Place("Pittsfield", "Sunny - 63°F", (None, "Springfield"), "44,057", "Linda Tyer"))
这也是在main()中生成玩家的地方:
player = Player(name, random.choice(places))
这是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
这是Player类构造函数:
class Player(object):
def __init__(self, name, curLoc):
self.name = name
self.curLoc = curLoc
稍后在Player类中我尝试使这个方法无济于事,因为令我沮丧的是,该类无法访问main()中的地方列表
def goWest(self):
for place in places:
if self.curLoc.connectedLocation[0] == place.name:
self.curLoc = place
答案 0 :(得分:0)
您需要通过向其添加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语句,因为我假设一旦找到当前位置,就不需要继续迭代列表了。