D
D
Dmitry Koldyaev2014-11-17 13:29:09
Python
Dmitry Koldyaev, 2014-11-17 13:29:09

How to call from the parent class to the static-function of the child?

I had such a task:
There is an abstract class

class BaseClass:
    @staticmethod
    def get_prefix():
        raise Exception('Переопределите этот метод в дочернем классе')

    @staticmethod
    def get_string_with_prefix(string=''):
        return BaseClass.get_prefix() + string

And here is the child class. In it, I don't want to duplicate the logic of the get_string_with_prefix function, but I just want to override the get_prefix function so that it returns a string corresponding to my class.
class ChildClass(BaseClass):
    @staticmethod
    def get_prefix():
        return 'child_class_prefix_'

So for example, if I call ChildClass.get_string_with_prefix('test'), then of course get_prefix is ​​called on BaseClass.
How can I solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2014-11-17
@mututunus

Use @classmethod

class BaseClass:
    @classmethod
    def get_prefix(cls):
        raise NotImplemented('Переопределите этот метод в дочернем классе')

    @classmethod
    def get_string_with_prefix(cls, string=''):
        return cls.get_prefix() + string

class ChildClass(BaseClass):
    @classmethod
    def get_prefix(cls):
        return 'child_class_prefix_'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question