好的,还有一个类型错误。这是我的代码:
class musssein:
def notwendig(self, name):
self.name = name
all = [] # fuer jede Eigenschaft eine extra Liste
day = []
time = []
prize = []
what = []
kategorie = []
with open(name) as f:
for line in f:
data = line.replace('\n','') #Umbruchzeichen ersetzen
if data != ' ': # immer nur bis zur neuen Zeile bzw. bis zum ' ' lesen
all.append(data) # in liste einfuegen
else:
kategorie.append(all.pop())
what.append(all.pop())
prize.append(all.pop())
time.append(all.pop())
day.append(all.pop())
def anzeige():
musssein.notwendig('schreiben.txt')
print table.Table(
table.Column('Datum', day),
table.Column('Kategorie', kategorie),
table.Column('Was?', what),
table.Column('Preis', prize, align=table.ALIGN.LEFT))
描述是用德语写的,但它解释了你可能已经知道的事情。
当我现在运行anzeige()
时,终端只显示:
File "test.py", line 42, in anzeige
musssein.notwendig('schreiben.txt')
TypeError: unbound method notwendig() must be called with musssein instance as first argument (got str instance instead)
我尝试了许多可能性,阅读了很多其他的线索,但我没有找到一个正确的解释它。
您的方法“notwendig”希望将musssein的一个实例作为其第一个参数,如果在musssein的一个实例上而不是在类本身上调用它,则这一过程是透明的:
相当于
另外,您的代码实际上并不存储来自文件的信息,而是存储在本地变量中,这些变量在方法退出时即被销毁。 您需要将方法更改为:
在下一个函数“anzeige”中,需要将它们更改为
newinstance.day
、newinstance.kategorie
等,否则将得到一个未定义的全局变量错误在调用类的方法之前,必须创建(实例化)类的对象
mussein
所以
notwendig
方法的self
参数是my_var
(mussein的一个实例)。顺便说一下,通常类名必须以大写字母开头。所以在这种情况下应该是
Mussein
。相关问题 更多 >
编程相关推荐