【问题标题】:Python Self - TypeError: add_state() takes exactly 4 arguments (3 given)Python Self - TypeError: add_state() 正好需要 4 个参数(给定 3 个)
【发布时间】: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__ 方法。

标签: python pandas


【解决方案1】:

缺少的参数是第一个,通常称为self,当您在类的实例上调用方法时会自动传递该参数。但是您没有在实例上调用add_state():您将其作为普通函数调用,并且必须传递所有四个参数。而你不能这样做,因为你没有任何类的实例,因为你仍在定义它。

您想编写一个__init__() 方法来执行add_state() 调用以及当前类主体中的所有其他事情。这样,就会有一个实例可以调用add.state()!像这样的:

def __init__(self):
    self.current_state = "A"
    self.home_state = "J"
    self.cost = 0

    self.index = range(1,20,1)
    self.columns = ["Current", "Choices", "Cost"]

    self.states = pd.DataFrame(columns=columns, index=index)

    self.counter = 1

    self.add_state("A", "B", 2)
    self.add_state("A", "C", 4)
    self.add_state("A", "D", 3)
    # and so on

【讨论】:

    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2012-03-15
    • 2014-05-06
    • 2016-07-16
    • 2013-06-12
    相关资源
    最近更新 更多