I'm using python and I want to be able to create an object of a base class and have it initialize the object using the __init__ of a subclass. I use a function defined outside of the classes to determine which subclass' __init__ method should be called. I found a way to make it work but its behaving in a way I don't understand.
To illustrate the strange behavior, I've written the following code. I create a base class (called parent). It has two subclasses (child1 and child2). In the __init__ of the base class, I call the function "choose" which returns an object of one of the derived classes (depending on the value of var). The strange thing is I can append to the array from the base class and it actually changes the array but when I try to change the value of a variable like "str", the "str" of base class does not change. I didn't really think this whole strange approach would work anyway but it confuses me because it half-works.
class parent: array =  str = "parent" def __init__(self, var): choose(var) class child1(parent): def __init__(self, var): self.array.append(var) self.str = "child1" class child2(parent): def __init__(self, var): self.array.append(var) self.str = "child2" def choose(var): if var == 1: child1_obj = child1(var) print child1_obj.array print child1_obj.str return child1_obj elif var == 2: child2_obj = child2(var) print child2_obj.array print child2_obj.str return child2_obj else: return None #testing code person = parent(2) print person.array print person.str
The output I receive is: