'Is there a way to use "parents" instanced methods in a "child" instance and iterate over multiple "parent" instances in a "child" instance?
Let's assume we have a class Person and a class Group
After I created instances of Person I add those to an instance of Group.
Now I want to use the same class methods from Person on a Group instance.
Is that possible with inheritance and those "Dunder Methods", __getitem__(), __iter__(), __next__() ?
class Group(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
'''
What do I need to add to also use `Person` class methods and those
methods iterate over the list `self.persons`
'''
class Person(object):
def __init__(self, name, status):
self.name = name
self.status= status
def print_info(self):
print(f'This is {self.name} with the status: {self.status}\n.')
def update_name(self, name):
self.name = name
def update_status(self, status):
self.status = status
p1 = Person("John", 0)
p2 = Person("Dave", 0)
p3 = Person("Susan", 0)
group = Group()
group.add_person(p1)
group.add_person(p2)
group.add_person(p3)
group.print_info()
#expected result:
#This is John with the status: 0.
#This is Dave with the status: 0.
#This is Susan with the status: 0.
group.update_status(1)
group.print_info()
#expected result:
#This is John with the status: 1.
#This is Dave with the status: 1.
#This is Susan with the status: 1.
Solution 1:[1]
Since the list has been saved in the member self.name, you can use that to iterate over.
def print_name(self):
for name in self.name:
print(f'This is {name}.')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
