Python - multiple inheritance with same name

大城市里の小女人 提交于 2019-12-12 03:34:55

问题


I have main class as:

class OptionsMenu(object):

    def __init__(self, name):
        try:
            self.menu = getattr(self, name)()
        except:
            self.menu = None

    @staticmethod
    def cap():
        return ['a', 'b']

and have a child class override as:

class OptionsMenu(OptionsMenu):
    @staticmethod
    def cap():
        return ['a', 'b', 'c']

The first class gives the menu options for default template, while next gives for some other template.

I want another class OptionsMenu derived from child class, and get the list (['a', 'b', 'c']) and make changes to that.

Is this achievable in python? If yes, how may I achieve this?

Many thanks for any help!


回答1:


Nothing stops you from getting result of parent's static function:

class OptionsMenu:
    @staticmethod
    def cap():
        return ['a', 'b', 'c']


class OptionsMenu(OptionsMenu):
    @staticmethod
    def cap():
        lst = super(OptionsMenu, OptionsMenu).cap()  # ['a', 'b', 'c']
        lst.append('d')
        return lst

print(OptionsMenu.cap())  # ['a', 'b', 'c', 'd']

But as noted to give same class names for different classes is very bad idea! It will lead to many problems in future.

Try to think, why do you want same names for different classes. May be they should have different names?

class OptionsMenu

class SpecialOptionsMenu(OptionsMenu)

Or may be as soon as cap() is static method, make different functions out of OptionsMenu?

def cap1(): return ['a', 'b', 'c']

def cap2(): return cap1() + ['d']


来源:https://stackoverflow.com/questions/36238999/python-multiple-inheritance-with-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!