For some reason most instances of classes are returning Type errors saying that insufficient arguments were passed, the problem is with self. This works fine:
class ExampleClass:
def __init__(self, some_message):
self.message = some_message
print ("New ExampleClass instance created, with message:")
print (self.message)
ex = ExampleClass("message")
However almost every other Class I define and call an instance of returns the same error. The almost identical function:
class Test(object):
def __init__(self):
self.defaultmsg = "message"
def say(self):
print(self.defaultmsg)
test = Test
test.say()
Returns a Type Error, saying that it needs an argument. I'm getting this problem not just with that class, but with pretty much every class I define, and I have no idea what the problem is. I just updated python, but was getting the error before. I'm fairly new to programming.
3 Answers 3
You have to instantiate the class:
test = Test() #test is an instance of class Test
instead of
test = Test #test is the class Test
test.say() #TypeError: unbound method say() must be called with Test instance as first argum ent (got nothing instead)
if you are curious you can try this:
test = Test
test.say(Test()) #same as Test.say(Test())
It works because I gave the class instance (self) to the unbound method !
Absolutely not recommended to code this way.
1 Comment
test = Test; test.say(test())You should add parentheses to instantiate a class:
test = Test()
Comments
Your test refers to the class itself, rather than an instance of that class. To create an actual test instance, or to 'instantiate' it, add the parentheses. For example:
>>> class Foo(object):
... pass
...
>>> Foo
<class '__main__.Foo'>
>>> Foo()
<__main__.Foo object at 0xa2eb50>
The error message was trying to tell you that there was no such self object to pass in (implicitly) as the function argument, because in your case test.say would be an unbound method.
Comments
Explore related questions
See similar questions with these tags.