问题描述
此问题中的后续操作,制定的不是很好.答案提供了一些其他的见解,因此现在我构建了一个有限的工作示例,对其进行了更好的解释.
A follow up from this question, which was not very well formulated. The answer provided some additional insight so now I have constructed a limited working example that explains it better.
基本上,我们有两个子类 A
和 B
和一个继承自这两个子类的 C
.类 A
和 B
都具有函数 MyFunc
,但功能不同.
Basically we have two subclasses A
and B
and a class C
which inherits from both. Classes A
and B
both have a function MyFunc
but which does different things.
我希望类 C
能够使用这两个函数,并且能够完全控制调用哪个函数,因为我希望对每个函数做不同的事情.下面的有限工作示例中的注释显示了我正在尝试做的事情.
I would like for class C
to be able to use both functions and have full control of which function is called since I wish to do different things with each function. The comment in the limited working example below shows what I am trying to do.
class A():
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
def MyFunc(self):
result = self.var1 + self.var2
return result
class B():
def __init__(self, var1):
self.var1 = var1
def MyFunc(self):
result = self.var1**2
return result
class C(A,B):
def __init__(self, var1, var2, var3):
A.__init__(self, var1, var2)
B.__init__(self, var3)
def MyFunc(self):
#in this function I want to call MyFunc from A and MyFunc from B. For example to add their results together
如何从 MyFunc
A 中的 MyFunc
和 B
中的 MyFunc
>在 C
中?
How can I call MyFunc
in A
and MyFunc
in B
from MyFunc
in C
?
推荐答案
您可以使用名称修饰来使子类中的类的属性可用,即使该子类定义了具有相同名称的属性.
You can use name mangling to make attributes from a class available in a child class even if that child defines an attribute with the same name.
class A():
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
def __MyFunc(self):
result = self.var1 + self.var2
return result
MyFunc = __MyFunc
class B():
def __init__(self, var1):
self.var1 = var1
def __MyFunc(self):
result = self.var1**2
return result
MyFunc = __MyFunc
class C(A,B):
def __init__(self, var1, var2, var3):
A.__init__(self, var1, var2)
B.__init__(self, var3)
def MyFunc(self):
return self._A__MyFunc() + self._B__MyFunc()
c = C(1, 2, 3)
print(c.MyFunc())
# 14
这篇关于从超类调用子类中的类似命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!