【发布时间】:2015-11-18 23:24:16
【问题描述】:
我正在尝试使用基于代理的模拟来解决驿马车问题。我正在尝试将状态添加到熊猫的数据框中。但是,执行此操作时,我收到错误“TypeError:add_state() 恰好需要 4 个参数(给定 3 个)”。我查看了 Stackoverflow 上的其他问题并尝试了解决方案,但是我缺少一些东西。
有人可以给我一些建议或提示,说明为什么我不断收到此错误吗?感谢您的宝贵时间。
from __future__ import division
import random
import pandas as pd
class stagecoach():
current_state = "A"
home_state = "J"
cost = 0
index = range(1,20,1)
columns = ["Current", "Choices", "Cost"]
states = pd.DataFrame(columns=columns, index=index)
counter = 1
def add_state(self, s_current, s_choices, s_cost):
self.states.loc[self.counter] = [s_current, s_choices, s_cost]
self.counter += 1
add_state("A", "B", 2)
add_state("A", "C", 4)
add_state("A", "D", 3)
add_state("B", "E", 7)
add_state("B", "F", 4)
add_state("B", "G", 6)
add_state("C", "E", 3)
add_state("C", "F", 2)
add_state("C", "G", 4)
add_state("D", "E", 4)
add_state("D", "F", 1)
add_state("D", "G", 5)
add_state("E", "H", 1)
add_state("E", "I", 4)
add_state("F", "H", 6)
add_state("F", "I", 3)
add_state("G", "H", 3)
add_state("G", "I", 3)
add_state("H", "J", 3)
add_state("I", "J", 4)
def choose(self,state):
states_to_choose = self.states[self.states.Current == state]
random_path = random.randint(0,len(states_to_choose))
current_state = states_to_choose[random_path]
def run(self):
while self.current_state != self.home_state:
print(self.states)
self.choose(self.current_state)
print(self.current_state)
self.cost += 1
game = stagecoach()
game.run()
【问题讨论】:
-
add_state 方法需要一个 self 参数。您可以通过调用 self.add_state 或传递驿马车实例来提供它。您可能打算将 add_state 调用放在
__init__方法中。 -
我认为以这种方式使用类是不对的。如果您要创建它的多个实例,它会产生很多副作用。使用新的样式类并定义
__init__方法。