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?
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)
+ 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...'
+ 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?
+ 1
Isn't that what inheritance is for?
0
Maybe... IDK
0
Yeah but I need to make 30 subclasses equal