Answer the question
In order to leave comments, you need to log in
How to have a common base class for dynamic instances?
Good afternoon!
Having fun with dynamic class creation, discovering the power of `types.new_class` and having a factory function like
def create_instance(cls_name, module, args=(), bases=()):
def clsexec(ns):
ns["__module__"] = module
if args:
ns["__reduce__"] = lambda self: args
cls = types.new_class(cls_name, bases, {}, clsexec)
return cls()
class Sample:
pass
main = [Sample(), Sample()]
pickle.dumps(main, protocol=2)
0: \x80 PROTO 2
2: ] EMPTY_LIST
3: q BINPUT 0
5: ( MARK
6: c GLOBAL 'source_module Sample'
43: q BINPUT 1
45: ) EMPTY_TUPLE
46: \x81 NEWOBJ
47: q BINPUT 2
49: h BINGET 1
51: ) EMPTY_TUPLE
52: \x81 NEWOBJ
53: q BINPUT 3
55: e APPENDS (MARK at 5)
56: . STOP
main = [create_instance("Sample", "source_code"), create_instance("Sample", "source_code")]
pickle.dumps(main, protocol=2
0: \x80 PROTO 2
2: ] EMPTY_LIST
3: q BINPUT 0
5: ( MARK
6: c GLOBAL 'source_module Sample'
43: q BINPUT 1
45: ) EMPTY_TUPLE
46: \x81 NEWOBJ
47: q BINPUT 2
49: c GLOBAL 'source_module Sample'
86: q BINPUT 3
88: ) EMPTY_TUPLE
89: \x81 NEWOBJ
90: q BINPUT 4
92: e APPENDS (MARK at 5)
93: . STOP
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question