Home > Blockchain >  If I return a class instance inside a class function, it creates a new object or it returns the exis
If I return a class instance inside a class function, it creates a new object or it returns the exis

Time:12-01

For example:

class DogOwners(object): def get_this_animal(id, dog_name): return Dog(id=id, name=dog_name)

Would this return a new object or the existing one associated to the *args of get_this_animal()?

It returns the data I want but I can't tell if now I have two dogs with the same data

CodePudding user response:

It would return a new dog with those attributes assuming that Dog(id=id, name =dog_name) is your constructor. The program doesn't have a way to instead return existing dogs with the same attributes as you've written it. If you wanted to not create a new dog then you'd need to store the data of all the dogs and search for that specific data to ensure you return the same dog. This storage and search can be done through several ways like a dictionary, array/list, and so on (likely a dictionary is better for what you're trying to do).

CodePudding user response:

Any time you run Dog(...), you're creating a new object (assuming you didn't do anything special to the class to change that fact). Calling a class as a function constructs a new instance by default. You can also check this yourself using id:

# I added the necessary 'self' parameter, and changed the 'id' parameter
def get_this_animal(self, dog_id, dog_name):
    new_dog = Dog(id=dog_id, name=dog_name)
    print(id(self), id(new_dog))  # These will not be the same
    return new_dog

That print will print two sepeate addresses/IDs, indicating that they're distinct objects. The dog_id and dog_name objects will be the same, however.

  • Related