我在下面的程序中得到了RecusionError,我无法找出原因。 请求专家帮助。
从Derived类调用Base类的方法foo导致 RecusionError
BaseKill():
def foo(self):
print('what is wrong with jpython')
return self.bar()
def bar(self):
print('just chill bar')
return None
class Derived(BaseKill):
def bar(self):
print('I am bar')
self.foo()
self.hello()
def hello(self):
print('say Hi')
if __name__== '__main__':
print('what')
b=BaseKill()
b.foo()
c = Derived()
c.bar()
答案 0 :(得分:1)
执行class Derived(BaseKill)
class Derived()
现在“继承”来自class BaseKill
的方法。
包括foo()
和bar()
。
但是,您bar()
中定义的class Derived()
优先于“已继承的bar()
”
基本上这与执行以下操作相似
class Derived():
def foo(self):
print('what is wrong with jpython')
return self.bar()
def bar(self):
print('I am bar')
self.foo()
self.hello()
def hello(self):
print('say Hi')
if __name__== '__main__':
print('what')
c = Derived()
c.bar()
通过此代码,您可以清楚地看到bar()
正在呼叫foo()
,而bar()
又会再次呼叫print
。这是一个无限/递归。
您看到的错误是正确的。
在原始代码中,您可以添加一些self
语句来获取print(self.__class__.__name__)
所代表的类的名称,例如@staticmethod
。这可以帮助您进一步了解类继承。
您可能希望BaseKill.bar()
查看class BaseKill():
def foo(self):
print('what is wrong with jpython')
return BaseKill.bar()
@staticmethod
def bar():
print('just chill bar')
return None
class Derived(BaseKill):
def bar(self):
print('I am bar')
self.foo()
self.hello()
def hello(self):
print('say Hi')
if __name__== '__main__':
print('what')
b=BaseKill()
b.foo()
c = Derived()
c.bar()
,但这会更改功能,因此请确保彻底测试以确保符合您的要求:
foo()
More information about @staticmethod
here
或者,您可以对BaseKill
中的class BaseKill():
def foo(self):
print('what is wrong with jpython')
return BaseKill.bar(self)
执行以下操作:
profiles
答案 1 :(得分:0)
Leason学会了:在调用同一类的方法时,在它们前面使用它的名字,比如BaseKill.bar(self) 来防止由于覆盖方法而导致的错误
BaseKill():
def foo(self):
print('what is wrong with jpython')
#return self.bar() ----Error 'self' referred to Calling class
return BaseKill.bar(self) #referred to same class method
def bar(self):
print('just chill bar')
return None
class Derived(BaseKill):
def bar(self):
print('I am bar')
self.foo()
self.hello()
def hello(self):
print('say Hi')
if __name__== '__main__':
print('what')
b=BaseKill()
b.foo()
c = Derived()
c.bar()