0

I wanted to use overloaded version of _get_all() in _get_all_odd(), is there a way to do it?

Calling it as BaseClass._get_all() raises an exception "Must be overloaded", calling it _get_all() gives a not recognised error.

########################################################################
class BaseClass:
  @staticmethod
  def _get_all():
    raise Exception("Must be overloaded")

  @staticmethod
  def _get_all_odd():
    result = [sh for sh in BaseClass._get_all() if sh%2 == 1]
    return result

##################################################################
class Shape(BaseClass):
  __all_shapes = [1, 2, 3]
  @staticmethod
  def _get_all():
    return Shape.__all_shapes

print(Shape._get_all_odd())
Yulia V
  • 3,507
  • 10
  • 31
  • 64
  • Is there a reason that you have the methods marked as `@staticmethod`? – quamrana Aug 10 '21 at 11:22
  • btw you don't mean `overload` (That would be having multiple methods of the same name in the same class), I think you mean `override` which is where a derived class provides a method which is executed in preference to the base class method. – quamrana Aug 10 '21 at 11:23
  • `BaseClass._get_all_odd()` should be a `@classmethod` and `BaseClass._get_all()` should be `cls._get_all()` – Alex Aug 10 '21 at 11:25
  • Does this answer your question? [Overriding a static method in python](https://stackoverflow.com/questions/893015/overriding-a-static-method-in-python) – Yevhen Kuzmovych Aug 10 '21 at 11:26
  • @Alex - thanks but could you explain why? it only uses `__all_shapes` , which is static (it is shared between all instances of `Shape`) – Yulia V Aug 10 '21 at 11:27
  • @YevhenKuzmovych - no. If you see how it could, please fix my snippet so that it works – Yulia V Aug 10 '21 at 11:28
  • 2
    @YuliaV see [this answer](https://stackoverflow.com/a/1669524/3279716). Briefly `@classmethod` implicitly gets the class it was called on (or the instance) so has access to overridden attributes and methods – Alex Aug 10 '21 at 11:32

1 Answers1

1

Is there a reason that you have to use a staticmethod? Using classmethods instead is functionally the same, but classmethods know more about the class structure.

For example, with minor changes, this works:

class BaseClass:
  @classmethod
  def _get_all(cls):
    raise Exception("Must be overloaded")

  @classmethod
  def _get_all_odd(cls):
    result = [sh for sh in cls._get_all() if sh%2 == 1]
    return result


class Shape(BaseClass):
  __all_shapes = [1, 2, 3]
  @classmethod
  def _get_all(cls):
    return Shape.__all_shapes

print(Shape._get_all_odd())