I wish I could do 2 things:
-
- Create as many times of the Child class from an instance of the Parent class (What I can do)
-
- Call a method of the Parent class from an instance of the Child class (What I can't do)
To illustrate my problem, I created 2 instances of the class Parent
to which I add an instance of the class Child
to each.
from datetime import datetime, timedelta
class Child:
def __init__(self):
pass
def ask_time(self): # This function doesn't work,
return self.read_time() # But I would like to be able to call here the "read_time()" method of the class "Parent"
class Parent:
def __init__(self, name, minutes_fast):
self.name = name
self.minutes_fast = minutes_fast
self.children = {}
def add_child(self, name): # Construct "Child" class instance from class "Parent" class instance
self.children[name] = Child() # Because of this line, I cannot inherit "class Child (Parent):"
def get_child(self, name):
if name not in self.children:
self.add_child(name)
return self.children[name]
def read_time(self):
current_time = datetime.now()
delta = timedelta(minutes=self.minutes_fast)
return (current_time + delta).strftime("%H:%M:%S")
# Add the Parent "James" who is 3 minutes early to his watch, and add him the child "John"
parent1 = Parent("James", 3)
child1 = parent1.get_child("John")
# Add the Parent "Michael" who is 1 minutes early to his watch, and add him the child "Matthew"
parent2 = Parent("Michael", 1)
child2 = parent2.get_child("Matthew")
print(parent1.read_time())
print(parent2.read_time())
In my use case, reading the time is the responsibility of the class Parent
. So I added the read_time()
method to this one.
But an instance of the class Child
must be able to request the time from the instance of the class Parent
that created it. So I add the ask_time()
method to the class Child
which calls the read_time()
method of the class Parent
... Which does not work without inheriting between my classes (from the following way class Child(Parent):
).
Which would allow me to do this, and what I now need to do.
print(child1.ask_time())
print(child2.ask_time())
But I don't see how to inherit when class Parent
itself depends on the class Child
?
Thanks for your help !