【发布时间】:2016-05-18 04:18:33
【问题描述】:
我很难找到 Python 继承问题的有效解决方案。
所以存在如下代码:
class Foo( object ):
def __init__():
self.some_vars
def foo_func():
x = Bar()
def foo_bar_func()
x += 1
class Fighters( Foo ):
def __init__():
Foo.__init__()
def func1():
Foo.some_attribute
def func2():
Foo.someother_func()
class Bar():
def bar_func():
#some stuff here
问题在于我需要覆盖Bar.bar_func(),但这有两个层次。我通过执行以下操作解决了它:
class Foo( Foo ):
def __init__():
Foo.__init__()
def foo_func(): #Overridden method
x = myBar()
class myFighters( Foo ):
def __init__():
Foo.__init__()
def func1():
Foo.some_attribute
def func2():
Foo.someother_func()
class myBar():
def bar_func(): #the function that I actually need to change
#my sweet code here
实际上唯一不同的是myBar.bar_func(),但我必须至少做两件我认为丑陋的事情。
一个是我必须创建一个继承自Foo 的class Foo。这似乎是一件奇怪的事情,并且不会让事情变得很清楚。我这样做是为了避免将myFighters 中的每个引用从Foo 重命名为myFoo。
第二个是我必须将所有代码从Fighters 复制到myFighters 中,唯一的目的是在Bar() 中使用覆盖函数。 Fighters 和 myFighters 完全相同,除了 Fighters 使用调用 Bar() 的 Foo 和 myFighters 使用调用 myBar() 的 Foo。有没有人有任何建议来解决这两个问题?或者我应该庆幸我找到了解决方案并继续我的生活......
【问题讨论】:
标签: python oop inheritance multi-level