0

I am trying to create a class with multiple functions, accepts a string as an argument and prints this string. So far this is what I have written:

class test():    
    def func(self,text):  
        print str(text)  
test.func('This is a bunch of text')  

To which I get the following error message:

_Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
TypeError: unbound method func() must be called with test instance as first argument   (got str instance instead)_  

Any suggestions?

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69

2 Answers2

5

You need to instantiate a class before you can call an instance method:

class Test(object):
    def func(self, text):
        print str(text)

test = Test()
test.func('This is a bunch of text')
Wooble
  • 87,717
  • 12
  • 108
  • 131
  • Thanks. You wouldn't happen to have a reference/link to someone intuitively explaining why this is the case? –  Dec 04 '13 at 12:54
2

Or you can try -

class test():
    @staticmethod
    def func(text):
        print str(text)
test.func('This is a bunch of text')
  • 2
    In general many people avoid staticmethods in Python because they're a good indication you didn't want a method at all but just a plain function. – Wooble Dec 04 '13 at 12:57