I have this code in test.py:
class Parent(object):
def __init__(self):
self.myprop1 = "some"
self.myprop2 = "thing"
def duplicate(self):
copy = Parent()
copy.myprop1 = self.myprop1
copy.myprop2 = self.myprop2
return copy
And this other in test2.py:
from test import Parent
class Child(Parent):
def __str__(self):
return "{}, {}".format(self.myprop1, self.myprop2)
obj1 = Child()
obj2 = obj1.duplicate()
obj2.myprop1 = "another"
obj2.myprop2 = "stuff"
# Accessing properties
print("obj1, ", obj1.myprop1, ", ", obj1.myprop2)
print("obj2, ", obj2.myprop1, ", ", obj2.myprop2)
# Using Child method
print("obj1,", str(obj1))
print("obj2,", str(obj2))
Running test2.py, the output is:
obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, <test.Parent object at 0x7fc1558e46d8>
I wonder if I can create an instance of Child inside Parent, but because there could be more child, I want to know the class of self and create an instance of that one class, copy the attributes and then return the object copy.
The goal for this code is to output this:
obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, another, stuff
This means that obj2 is a Child object instead of a Parent object.
Hope this is clear, thanks!
EDIT: I don't want to use copy.copy()
or copy.deepcopy()
. If you want to get only a copy and implement a simpler solution, check Moberg comment to see another related question that uses those functions.
But, this question is intended to get another way of doing that and also know how to get the Class from an object and get another instance of that same Class. This particular case, is showing a relationship of parent-child between classes, that I added to show the whole context of my doubt.