Reputation: 1875
I am learning Python as a beginner and I'd like to create a class Person
. In the constructor I would want to put every instance I create into a set called 'instances'. Then I'd like the instances() method to return all the instances. How can I do this?
class Person:
# Type annotations
__first_name: str
__last_name: str
instances: set
# Initializing variables
no_of_persons = 0
instances = set()
def __init__(self, firstname="unknown", lastname="unknown"):
self.__first_name = firstname
self.__last_name = lastname
Person.no_of_persons += 1
Person.instances.add() ## Here I have problems
@property
def first_name(self):
return self.__first_name
@first_name.setter
def first_name(self, firstname):
self.__first_name = firstname
@property
def last_name(self, ):
return self.__last_name
@last_name.setter
def last_name(self, lastname):
self.__last_name = lastname
def getFullName(self):
""" Returns a tuple of the firstname and the lastname """
return (self.__first_name, self.__last_name)
def summary(self):
""" Returns a dictionary of all instance variables """
return {'first_name': self.__first_name,
'last_name': self.__last_name}
@staticmethod
def number_of_persons():
return Person.no_of_persons
@staticmethod
def instances():
return Person.instances
p1 = Person()
Person.number_of_persons()
Person.instances()
Upvotes: 4
Views: 9214
Reputation: 599580
You need to add self
to the set.
Person.instances.add(self)
or more idiomatically
self.__class__.instances.add(self)
Also, you need to use a different name for the method that gets the instances; and it should be a classmethod, not a staticmethod.
@classmethod
def get_instances(cls):
return cls.instances
Although really you don't need a method here at all, as you can access Person.instances
(the attribute) directly.
Upvotes: 9