Home > Software engineering >  Dynamically created instances in python
Dynamically created instances in python

Time:01-27

I have definition of parent class "Parent". I have also defined child classes "child1", "child2". In child's some of the functions are overided some not. But the problem is that number of instances will be defined in .ini file. Question is how to dynamically create this instances. I have tried with "type" but it is not working. Below code with comments

`

class Parent:
    def __init__(self, var_1):
        self.var_1 = var_1
    
    def method1(self):
        print("method1")
    
    def method2(self):
        print('method2')
    
class child1(Parent):
    def __init__(self, var_1, var2):
        self.var2 = var2
        super().init(var_1)
    
    def method2(self):
        print('method2_own_implementation')

class child2(Parent):
    def __init__(self, var_1, var2):
        super().__init__(var_1)
        self.var2 = var2

    
    def method1(self):
        print("method1_own_implementation")

#4 below lines it is how it normally works

A = child1(2, 'XXX')
A.method2()
B = child2(3, 'sfsaf')
B.method1()

#list_nr define that 2 object of both types should be created, how to do it programmatically?
list_nr = ['child1', 'child1', 'child2', 'child2']

i tried with type, but not working as expected

list_classes = {'child1':child1, 'child2':child2}    

created_instances = []

for index, type_obj in enumerate(list_nr):
    A = type(('type_obj'   str(index)), (list_classes[type_obj],), {'var_1': 3, 'var2': 'xxx'})
    created_instances.append(A)

print(created_instances[0].method1())
    

after executing this receiving error:

print(created_instances[0].method1()) TypeError: method1() missing 1 required positional argument: 'self'

CodePudding user response:

Not sure if I fully understood your question, but I'm guessing you just want created_instances to contain instance of the classes listed in list_nr with the variable var_1 initialized to 3 and var2 initialized to XXX? If so you are overcomplicating it a bit here is a modified version of your code that does so.

class Parent:
    def __init__(self, var_1):
        self.var_1 = var_1

    def method1(self):
        print("method1")

    def method2(self):
        print('method2')


class child1(Parent):
    def __init__(self, var_1, var2):
        self.var2 = var2
        super().__init__(var_1)

    def method2(self):
        print('method2_own_implementation')


class child2(Parent):
    def __init__(self, var_1, var2):
        super().__init__(var_1)
        self.var2 = var2

    def method1(self):
        print("method1_own_implementation")


# 4 below lines it is how it normally works

A = child1(2, 'XXX')
A.method2()
B = child2(3, 'sfsaf')
B.method1()

# list_nr define that 2 object of both types should be created, how to do it programmatically?
list_nr = ['child1', 'child1', 'child2', 'child2']

list_classes = {'child1': child1, 'child2': child2}

created_instances = []

for index, type_obj in enumerate(list_nr):
    A = list_classes[type_obj](var_1= 3, var2= 'xxx')
    created_instances.append(A)

print(created_instances[0].method1())

The main change I've done is change this line

A = type(('type_obj'   str(index)), (list_classes[type_obj],), {'var_1': 3, 'var2': 'xxx'})

to

A = list_classes[type_obj](var_1= 3, var2= 'xxx')

list_classes[type_obj] is the same thing as the class you want class1 or class2 so it's essentially the same as

A = child1(var_1= 3, var2= 'xxx')  # or child2 depending on what type_obj is 

Also for some unelicited advice. In the future you might want to reduce the question example to the minimal, reproducable example. For your case your problem had nothing to do with method overloading so you didn't need to include the parent in the example.

  • Related