简体   繁体   中英

How to get all instances of a class

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()

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.

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