【发布时间】:2019-10-18 14:03:11
【问题描述】:
我有几个类,它们的方法都遵循相同的结构。为了这个例子,让我们说它是
class Foo:
def say_hello(self,a,b,c,d) : print("hello" + a + b + c + d)
def say_moo(self,a,b,c,d) : print("moo" + a + b + c + d)
def say_foo(self,a,b,c,d) : print("foo" + a + b + c + d)
# more of the same pattern...
class Bar:
def say_hello(self,a,b,c,d) : print("hello" + a + b + c + d)
def say_bar(self,a,b,c,d) : print("bar" + a + b + c + d)
def say_boo(self,a,b,c,d) : print("boo" + a + b + c + d)
#more classes of the same pattern...
拥有这些方法是必需的,因此不幸的是,简单地使用def say_x(self,x,a,b,c,d) : print(x + a + b + c + d) 并不是解决方案。
我想避免重复自己,并且正在寻找一种方法来写一些类似的东西
class Foo :
def SOME_MAGIC("hello")
def SOME_MAGIC("moo")
def SOME_MAGIC("foo")
这将导致相当于上述Foo。搜索主题时,我总是使用元类找到一些东西,但它们总是带有注释:“如果你想知道是否需要它们,你就不需要。”。因此,显然我不需要它们。我需要什么?
【问题讨论】:
-
您可以在这里利用继承。使类
Foo和Bar从另一个单独的类继承SOME_MAGIC,例如BarStool。 -
@HampusLarsson 大多数方法在
Foo和Bar(以及其他)中都不同,只有少数例外。我知道我可以将say_hello移动到基类,但这就是我所知道的如何在这里使用继承
标签: python python-2.7 class