python多重继承 同名函数_Python-具有相同名称的多重继承

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!

解决方案

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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值