Given the following requirements:
Foundation
and Data
Data
is a child class of Foundation
Foundation
hold an instance of Data
Python
code:
from __future__ import annotations
class Foundation():
data: Data
def __init__(self):
self.data = Data()
class Data(Foundation):
pass
Foundation()
However, the given script exits with an RecursionError
. Why and how can I implement the three given requirements?
You can use super
to avoid calling an object that calls an object that calls an object... and so on untill recursion error.
from __future__ import annotations
class Foundation():
def __init__(self, data):
self.data = data
print(self.data)
class Data(Foundation):
def __init__(self):
super(Data, self).__init__(self)
Data()
Now you called Data
, and data's super
is a Foundation
, which holds a reference to it's child.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.