Найти - Пользователи
Полная версия: Вызываю метод объекта, но вызывается @staticmethod с тем же именем -- что я сделал не так?
Начало » Python для новичков » Вызываю метод объекта, но вызывается @staticmethod с тем же именем -- что я сделал не так?
1
fshshsh
Изучаю тему, сделал тест в консоли пайтона:
 class A():
    def foo(self):
       print('object method')
    @classmethod
    def foo(cls):
       print('class method')
    @staticmethod
    def foo():
       print('static method')
obj = A()
obj.foo()
static method
A.foo()
static method

Подскажите, пожалуйста, что я сделал не так?
JOHN_16
вы в корне не правильно поняли тему. Это работает совершенно не так
JOHN_16
Вот посмотрите на пример использования
 >>> class A:
...     def foo(self):
...        print('object method', type(self))
...
>>>
>>> class B:
...     @classmethod
...     def foo(cls):
...        print('class method', type(cls))
...
>>>
>>> class C:
...     @staticmethod
...     def foo():
...        print('static method')
...
>>>
>>>
>>>
>>>
>>>
>>>
>>> A().foo()
object method <class '__main__.A'>
>>> A.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'self'
>>>
>>>
>>>
>>> B().foo()
class method <class 'type'>
>>> B.foo()
class method <class 'type'>
>>>
>>>
>>>
>>> C().foo()
static method
>>> C.foo()
static method
Rodegast
> но вызывается @staticmethod с тем же именем – что я сделал не так?

У всех методов должны быть разные имена, иначе последующий метод будет переопределять предыдущий с тем же именем.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB