简体   繁体   中英

How to inherit from a base class, when the inheriting class requires the inherited class in Python?

Given the following requirements:

  1. We have the classes Foundation and Data
  2. Data is a child class of Foundation
  3. Instances of 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.

Tutorial

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM