在另一个文件中覆盖类的方法 [英] Override method of class in another file
问题描述
假设我有两个文件, file1.py 和 file2.py 。在 file1.py 中,我定义了两个类,一个从另一个继承:
Say I have two files, file1.py and file2.py. In file1.py, I define two classes, one inherits from the other:
file1.py: / p>
file1.py:
class Class1:
def __init__(self):
pass
def func1(self):
return "Hello world!"
class Class2(Class1):
def __init__(self):
pass
def func2(self):
return self.func1()
$ b 和 func2()
来自 Class2
。
file2.py:
import file1
class Class3(file1.Class2):
def __init__(self):
pass
问题:如何在 file2中更改 func1()
从 Class1
以使 Class2
中的 func2()
返回与 func1()
?
Question: How can I change func1()
from Class1
in file2.py, so that func2()
in Class2
returns the same as func1()
?
不是这样:
class Class3(file1.Class2):
...
def func1(self):
return "Another string"
推荐答案
将覆盖 func1
工作?
Would overriding func1
work?
class Class(file1.Class2):
def func1(self):
print "Class3.func1"
c = Class3()
c.func2()
code>未在 Class3
,,Class2.func2
中定义code> 。但是,在该函数的正文中, self
仍然是 Class3
的实例,因此 self.func1()
调用 Class3.func1
,而不是 Class1.func1
。这不同于
Since func2
is not defined in Class3
, Class2.func2
is called. However, in the body of that function, self
is still an instance of Class3
, so self.func1()
calls Class3.func1
, not Class1.func1
. That is different from
d = Class2()
d.func2()
其中 self
在 Class2.func2
是 Class2
的实例。 Class2
未定义 func1
,因此 Class1.func1
调用。
where self
in Class2.func2
is an instance of Class2
. Class2
does not define func1
, so Class1.func1
is called.
这篇关于在另一个文件中覆盖类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!