pokeswap
pokeswap

Reputation: 15

Python my Class throws TypeError

here is my code.

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)

When I run the program, I enter a question (I know that the program does not care what is entered). I think I did something wrong with the class. I know it works fine when there is no class: statement, but I need the class there (after I am done, I am going to use this as a module).

After the question, I get

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

(I did not add any error checking yet. I will try to add try and catch/raise for if the file ./crazy8 does not exist. Also, I am later going to add a file that will automatically sys("touch ./crazy8") (on Mac/linux) and, after I find out how to create a file on Windows, I will add that.

Upvotes: 0

Views: 63

Answers (2)

Awalrod
Awalrod

Reputation: 268

You need to create and instance or object of the class(same thing).
x = crazy8()
x.fortuner(r,"./crazy8")

It's also considered common practice to have your classes start with capital letters and instances with lowercase.
class Crazy8
crazy8 = Crazy8()

Hope this helps

Upvotes: 1

01zhou
01zhou

Reputation: 334

Either you should create an instance of the class and call its method, or you should make the method static.

Please refer to:

Static methods in Python

Upvotes: 0

Related Questions