Can u make a class factory in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can u make a class factory in python?

I mean, in a code I had like thirty classes that basically are the same with one thing different, so could I make a class factory like the design pattern but instead of objects makes classes and after make a factory that makes objects through those classes?

18th Feb 2019, 5:36 PM
Eloý Pascual
Eloý Pascual - avatar
6 Answers
+ 8
you can store different attributes in a tuple and use type() to create classes using a list comprehension class Base: a = 0 subs = [type('sub' + str(x), (Base,), {'a': x}) for x in range(1, 21)] print(Base.a) for sub in subs: print(sub.a) Or you can use a list comprehension to create attributes like this class Base: a = 0 attrs = ( { '__init__': lambda self, a: setattr(self, 'a', a) or setattr(self, 'b', x), '__repr__': lambda self: '(' + repr(self.a) + ', ' + repr(self.b) + ')' } for x in range(1, 20) ) subs = [type('sub' + str(x), (Base,), attr) for x, attr in enumerate(attrs, 1)] for i, sub in enumerate(subs): print(sub(i)) print(Base.a)
18th Feb 2019, 7:22 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 2
Read on a bit in your tutorial - I'm confident that the modules about inheritance will give you what you desire! Basically it goes like this: You design a 'mommy' class that has all the properties your classes are supposed to share. Then you write 'children' classes that define only what's different. These definitions will look like: 'Be just like mommy, except...'
18th Feb 2019, 6:20 PM
HonFu
HonFu - avatar
+ 2
If every subclass has only one or two methods, that won't string out so long. But maybe you tell us what exactly you're trying to do?
18th Feb 2019, 6:29 PM
HonFu
HonFu - avatar
+ 1
Isn't that what inheritance is for?
18th Feb 2019, 6:10 PM
HonFu
HonFu - avatar
0
Maybe... IDK
18th Feb 2019, 6:11 PM
Eloý Pascual
Eloý Pascual - avatar
0
Yeah but I need to make 30 subclasses equal
18th Feb 2019, 6:21 PM
Eloý Pascual
Eloý Pascual - avatar