Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Being forced to pass an object itself when calling class methods - am I doing it wrong?

Tags:

python

class

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?

like image 683
user1066886 Avatar asked Dec 26 '22 13:12

user1066886


1 Answers

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()
like image 79
Jim Avatar answered Dec 28 '22 05:12

Jim