Yulia V
Yulia V

Reputation: 3559

How to use overloaded static method in a base class?

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())

Upvotes: 0

Views: 86

Answers (1)

grumpysmudge
grumpysmudge

Reputation: 26

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())

Upvotes: 1

Related Questions