Python-具有相同名称的多重继承 [英] Python - multiple inheritance with same name

查看:184
本文介绍了Python-具有相同名称的多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主班是:

class OptionsMenu(object):

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

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

并将子类覆盖为:

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.

我想要从子类派生的另一个类OptionsMenu,并获取列表(['a', 'b', 'c'])并对其进行更改.

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

这在python中可以实现吗?如果可以,我该如何实现?

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

非常感谢您的帮助!

推荐答案

没有什么可以阻止您获取父级静态函数的结果:

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)

还是cap()是静态方法,可能会在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']

这篇关于Python-具有相同名称的多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆