Skip to content

Instantly share code, notes, and snippets.

@komuw
Last active June 19, 2019 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/e202c2f1405c9ff0d709abfe4466c4a3 to your computer and use it in GitHub Desktop.
Save komuw/e202c2f1405c9ff0d709abfe4466c4a3 to your computer and use it in GitHub Desktop.
python create a new class instance inside same class
import copy
# see: https://stackoverflow.com/questions/13260557/create-new-class-instance-from-class-method
class Animal(object):
request_id = "Original_Animal"
def reproduce(self):
"""
gives birth to new instances of Animal
"""
print("Original_Animal_id: ", id(self))
new_animal_A = self.__class__()
new_animal_A.request_id = "Animal_A"
new_animal_B = type(self)()
new_animal_B.request_id = "new_animal_B"
new_animal_C = copy.deepcopy(self.__class__())
new_animal_C.request_id = "new_animal_C"
self.printer()
new_animal_A.printer()
new_animal_B.printer()
new_animal_C.printer()
def printer(self):
print()
print("id_of_self:", id(self))
print("request_id: ", self.request_id)
a = Animal()
a.reproduce()

python instance_creator.py

Original_Animal_id:  4362149000

id_of_self: 4362149000
request_id:  Original_Animal

id_of_self: 4362149056
request_id:  Animal_A

id_of_self: 4362149168
request_id:  new_animal_B

id_of_self: 4362981272
request_id:  new_animal_C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment