I'm messing around with classes and data flow and I am having difficulties creating a list of classes inside the class (to give control of the list to the class in itself).
class Person:
listOfPeople = []
def __init__(self, name, age):
self.name = name
self.age = age
self.listOfPeople = []
def set_age(self, age):
if age <= 0:
raise ValueError('The age must be positive')
self._age = age
def get_age(self):
return self._age
def AppendList(self):
self.listOfPeople.append(self)
def returnList(self):
return self.listOfPeople
age = property(fget=get_age, fset=set_age)
john = Person('John', 18)
barry = Person("Barry", 19)
john.AppendList()
barry.AppendList()
print(Person.listOfPeople)
The output is simply
[]
Let´s use this example. I want the class Person to have a list of people. That list of people has instances of the class it's in. I want the entire program to have access to this class, regardless of having an instance initialised. Is it even possible to do what I want in Python?
My expected output is a list with the 2 instances I added to the list.