【发布时间】:2013-08-24 12:39:42
【问题描述】:
我想要一个 python 类,它部分由来自其他类的特定方法组成,这些方法在“组合类”中的 self 上运行。我该怎么做?
例如如果我想在我的新类“theClass”中包含来自 classA 和 classB 的特定方法:
# Some classes to "inherit" from
class classA(object):
def methA1(self, value):
self.attrib = value*1
def methA2(self, value):
self.attrib = value*2
class classB(object):
def methB1(self, value):
self.attrib = value*3
def methB2(self, value):
self.attrib = value*4
# The class I want to build
class theClass(object):
# WHAT TO DO HERE?
# -------------------
methA1 = classA.methA1
methB2 = classB.methB2
# -------------------
# /WHAT TO DO HERE
# add additional methods...
def methC(self, value):
self.attrib = value*5
# I want the following behavior
instance = theClass()
instance.methB2(5) # sets instance.attrib to 20
instance.methA2(5) # error, does not exist
【问题讨论】:
-
这应该可以工作,至少在 Python 3 中。你的问题/问题是什么?
-
@AshwiniChaudhary 这并没有给出关于
methA2和methB1的预期行为。 -
@delnan 哦!没看到这条线:
# error, does not exist
标签: python class inheritance methods code-reuse