I've just started learning about object orientated python and in the course I was taking, one of the first things done was to understand the error this code gives.
class NewList():
def first_method():
print("hello")
instance = NewList()
instance.first_method()
Here is the error.
---------------------------------------------------------------------
TypeError Traceback (most recent call last)
ipython-input-44-9e10ffed0a3f in module()
----> 1 instance.first_method()
TypeError: first_method() takes 0 positional arguments but 1 was given
My understanding is that when you call a method belonging to a particular object, python actually does this instead:
instance.first_method(instance)
But as we haven't given our method any positional arguments, there is an error.
I tried to experiment with this using other classes. I took the string class and tried the same thing.
instance_2=str()
result=instance_2.title()
print(result)
Here there was no error. My reasoning was that in the source code somewhere ( I tried to look and find out myself but I couldn't make sense of it) when defining the title method, it was given a 'self' argument. I.e, in my head I thought the print result code did this:
print(instance_2.title(instance_2))
So 1 argument was required by the method and one was given. I decided to find out how many arguments the title() method actually took by purposefully adding in an extra argument, to see the error message.
instance_2=str()
result=instance_2.title(instance_2)
print(result)
Here, I figured that I would get an error saying I have given 2 positional arguments but title() only takes 1.
Instead, I got this.
TypeErrorTraceback (most recent call last)
<ipython-input-1-a25ae25c09cc> in <module>()
1 instance_2=str()
----> 2 result=instance_2.title(instance_2)
3 print(result)
TypeError: title() takes no arguments (1 given)
My concerns are why it says I only gave 1 argument when in the very first case, I have none and it still said I gave 1, I assumed 1 was always given by default. This is apparently not so. I even tried doing the same thing (adding an extra argument) to my first code):
class NewList(DQ):
def first_method():
print("hello")
instance=NewList()
instance.first_method(instance)
This was the error(skipped the fluff at the start)
TypeError: first_method() takes 0 positional arguments but 2 were given
So there is clearly an extra argument being given here. Why isn't this same phantom argument coming up in the string case?