__init __()缺少4个必需的位置参数:

时间:2018-10-05 17:29:00

标签: python

我已经创建了以下代码,但是我不断收到错误消息: TypeError: __init__()缺少4个必需的位置参数:'exercise''friendliness''intelligence''drool'

这是我的下面的代码:

class Dog_card_player: #creates the class
    def __init__(self,name, exercise, friendliness, intelligence, drool):
        self.name = name
        self.exercise = exercise#.random.randint(1,100)
        self.friendliness = friendliness#.random.randint(1,100)
        self.intelligence = intelligence#.random.randint(1,100)
        self.drool = drool#.random.randint(1,100)

    def Card_stats_player(self): #creates the stats for the card
        print("Name: " + self.name)
        print("Exercise: " + self.exercise)
        print("Friendliness: " + self.friendliness)
        print("Intelligence: " + self.intelligence)
        print("Drool: " + self.drool)


def Printing_card_player():
    with open ("dogswrite.txt") as f1:
        Dog_name_player = Dog_card_player(f1.readline())
        Dog_name_player.Card_stats_player()


Printing_card_player()

3 个答案:

答案 0 :(得分:1)

.readline()方法仅返回一个字符串,而.readlines()返回一个列表。当您需要多个字符串时,您将提供1个字符串作为类的参数。

答案 1 :(得分:1)

您必须将f1.readline()的结果解析为单独的参数

假设文本文件的格式如下

spot, 1, 2, 3, 4

会是这样

m_input = f1.readline()
m_input = m_input.split(',')

Dog_name_player = Dog_card_player(m_input[0], m_input[1], m_input[2], m_input[3],m_input[4] )

答案 2 :(得分:0)

您以这样的方式定义了您的类:5个类需要 5个参数才能创建:

class Dog_card_player: #creates the class
    def __init__(self,name, exercise, friendliness, intelligence, drool):

如果在创建对象时假定一行包含五个参数,则应从该行“提取”它们。也就是说,代替

Dog_name_player = Dog_card_player(f1.readline())

您应该有类似的内容:

line = f1.readline()
pars = line.split() # or line.split(',') for a comma-separated list
if len(pars) < 5:
    print("Not enough arguments")
    return
Dog_name_player = Dog_card_player(*pars)

如果每行总是恰好有五个参数,那么您可以简单地执行以下操作:

Dog_name_player = Dog_card_player(*f1.readline().split())