Python我的类抛出TypeE

2024-05-16 04:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。你知道吗

import fileinput, random
from os import system as sys
from sys import exit
class crazy8(object):
    question = raw_input("please enter a yes or no question \n")
    def fortune(self, filex, current):
        current = r"./"
        fortunes = list(fileinput.input(filex))
        sys("cd", current)
        print random.choice(fortunes)
crazy8.fortune(r"./crazy8")
exit(0)

当我运行程序时,我输入一个问题(我知道程序不关心输入的内容)。我想我在课堂上做错了什么。我知道它在没有class:statement的情况下工作得很好,但是我需要那里的类(完成之后,我将把它用作一个模块)。你知道吗

问完这个问题,我明白了

TypeError: unbound method fortune() must be called with crazy8 instance as first argument (got str instance instead)

(我还没有添加任何错误检查。如果文件./crazy8不存在,我将尝试添加try和catch/raise。另外,我稍后将添加一个文件,该文件将自动sys(“touch./frazy8”)(在Mac/linux上),在我了解如何在Windows上创建文件之后,我将添加该文件。你知道吗


Tags: 文件fromimportinputassysexitrandom
2条回答

您需要创建类的实例或对象(相同的东西)。
x = crazy8()
x.fortuner(r,"./crazy8")

通常的做法是以大写字母开头,以小写字母开头。
class Crazy8
crazy8 = Crazy8()

希望这有帮助

要么创建类的实例并调用其方法,要么使该方法成为静态的。你知道吗

请参考:

Static methods in Python

相关问题 更多 >