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

If I made some function as follows:

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 a python shell:

>>> s = Counter
>>> s.count()

As a result, I get the following:

TypeError: count () missing 1 required positional argument: 'self'

Am I doing something wrong? I don’t understand why I would have to pass the object myself in my own way. I thought it was automatically passed because I am accessing a method using a period. At least it is so (I remember, possibly incorrectly) that it is in C ++, so it makes no sense to me that it will be so in python. Am I doing something wrong?

Basically, why should I pass it to s.count (s), and not just s.count (). Should I already initialize the variable before the period?

+4
2
s = Counter

Counter. Counter s. , .

Counter, :

s = Counter()
+9

:

1) def count(self) -> int: def reset(self) -> None:, , , -> int/None.

2) , s = Counter() s = Counter.

:

class Counter:
    def __init__(self):
        self._count = 0

    def count(self):
        self._count += 1
        return self._count

    def reset(self):
        self._count = 0

s = Counter()
print s.count()
+1

Source: https://habr.com/ru/post/1528056/


All Articles