If I made some sort of function like this:
class Counter:
def __init__(self):
self._count = 0
def count(self) -> int:
self._count += 1
return self._count
def reset(self) -> None:
self._count = 0
and put this in the python shell:
>>> s = Counter
>>> s.count()
I end up with this:
TypeError: count() missing 1 required positional argument: 'self'
Am I doing something wrong? I don't understand why I would have to pass an object itself for its own method. I thought that it is automatically passed because I access the method using the period. At least this is how (I remember, perhaps incorrectly) it being in C++ so it doesn't make sense to me that this would this way in python. Am I doing something wrong?
Basically, why do I need to pass it s.count(s) rather than just do s.count(). Shouldn't self already initialize to the variable before the period?
s = Counter
This doesn't create an instance of the Counter
class. It assigns the Counter
class to the variable s
. This means that you're trying to call an instance method on the class itself in the second line.
If you want to create an instance of the Counter
class, you should write:
s = Counter()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With