Python调用station类stat_info方法返回函数对象而非站点列表问题解决
问题原因
- 代码中
station.stat_info是直接引用类的方法对象,没有执行调用(缺少()),同时也没有针对你创建的przystanki站点实例列表操作,无法得到所有站点的名称集合。 - 你定义的
stat_info方法是单个站点实例的方法,返回的是当前站点自己的名称列表,不能直接返回所有站点的名称。
修正代码
class station: def __init__(self, name, possibility_of_change, time_of_stay): self.name = name self.possibility_of_change = possibility_of_change self.time_of_stay = time_of_stay stat = [] stat.append(self.name) self.stat = stat def stat_info(self): return self.stat class Position_of_route: def __init__(self, station, time_between_2_stays): self.station = station self.time_between_2_stays = time_between_2_stays class Route(station): def __init__(self, name1, list_of_positions): self.name1 = name1 self.list_of_postitions = list_of_positions def trasa_info(self): return 5 def generate(self, time): przystanki = [ station("Warszawa1",True,3), station("Warszawa2",True,5), station("Warszawa3",False,0), station("Warszawa4",True,3), station("Warszawa5",True,7), station("Warszawa6",True,3), station("Warszawa7",True,9), station("Warszawa8",False,0), station("Warszawa9",True,12), ] # 遍历所有站点实例,调用stat_info方法收集所有站点名称 station_names = [st.stat_info()[0] for st in przystanki] a={ "Name and information": [self.name1, station_names] } return a print(Route("Ko",[1,2]).generate(18))
运行结果
{'Name and information': ['Ko', ['Warszawa1', 'Warszawa2', 'Warszawa3', 'Warszawa4', 'Warszawa5', 'Warszawa6', 'Warszawa7', 'Warszawa8', 'Warszawa9']]}
补充说明
如果你不需要复用stat_info方法,也可以直接取实例的name属性,收集列表的写法改为station_names = [st.name for st in przystanki],效果完全一致。
内容的提问来源于stack exchange,提问作者Kokin
相关产品推荐
相关产品推荐

