【问题标题】:TypeError: str takes exactly 2 arguments errorTypeError: str 恰好需要 2 个参数错误
【发布时间】:2013-12-08 21:05:46
【问题描述】:

我在获取所需的输出时遇到问题。我正在使用具有 3 个已定义类的模块(称为 q3.py):Student、Module 和 Registrations,并将其实现到具有以下详细信息的另一个文件中:

#testq3.py
from q3 import *

james = Student('james')
alice = Student('alice')
mary = Student('mary')

agm = Module('agm')
ipp = Module('ipp')

r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)

mstr = ''
for m in map(str,r.modules(alice)):
    mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
    sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)

print(r)

然后这是我的 q3.py 文件...

class Student:    
    'Class to define student details'
    def __init__(self, name):
        self.name = name
    def __str__(self, name):
        return (self.name)
    def __iter__(self, name):
        return iter(self.name)

class Module:    
    'Class to define module codes'
    def __init__(self, modules):
        self.modules = modules    
    def __str__(self, modules):
        return self.modules
    def __iter__(self, modules):
        return iter(self.modules)


class Registrations():
    'Class telling us what modules students are taking'
    def __init__(self):
        self.reglist = []
    def add(self, students, modules):
        self.reglist.append((students, modules))
    def students(self, modules):
        for x in self.reglist:
            if x[1] == modules:
                print x[0]
    def modules(self, students):
        for y in self.reglist:
            if y[0] == students:
                print y[1]

我不断收到以下错误:

Traceback (most recent call last):
  for m in map(str,r.modules(alice)):
File ".....", line 37, in modules
  print y[1]
TypeError: __str__() takes exactly 2 arguments (1 given)

所以我添加了 striter,因为我也不断收到参数 2 迭代错误。我哪里错了?我只是希望输出与 testq3.py 底部的输出相同。请帮忙??我很确定我有很多 str/iter 错误,但肯定还有一些我遗漏的东西,因为尽管玩了很长时间,但我没有得到任何接近我想要的输出的地方。任何帮助将不胜感激!

【问题讨论】:

  • 您应该删除提出第二个问题的编辑,然后在另一个问题中提出第二个问题。就目前您编辑的问题而言,您的标题毫无意义,答案也毫无意义。这样做被认为是不好的形式......请问第二个问题。
  • 对不起,我是新手,不知道,我会记住的。

标签: python string class


【解决方案1】:

您的 __str__ 方法需要一个额外的参数,但 Python 在打印对象时没有传递该参数。

例如:

def __str__(self, modules):
    return self.modules

您需要确保所有__str__ 方法都具有def __str__(self): 作为签名。例如:

def __str__(self):
    return self.modules

【讨论】:

  • 啊,你建议我把它改成什么?
【解决方案2】:

您的 __str____iter__ 方法采用了不必要的 modules/name 参数。 Python 不会从 str 函数中传递它,而且你也没有使用它,所以只需从这些方法的参数列表中删除它即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2021-10-29
    • 2023-04-04
    • 1970-01-01
    • 2012-02-14
    • 2021-04-25
    相关资源
    最近更新 更多