This seems to work and do what you want. Theself.foo = self.anArg + 3
statement had to be changed toself.foo = self.anArg + "3"
to avoid aTypeError
when attempting to concatenate astr
and anint
objects which is what happens with acls('f00')
call as shown in the code in your question.
import types
class VeryImportantSuperClass(object):
def __init__(self, anArg, anotherArg):
self.anArg = anArg
#Extremely clever code here
def createSubclassAttempt1(name):
source = ('def __init__(self, arg):\n'
' super(' + name + ', self).__init__(arg, 6.02e23)\n'
' self.foo = self.anArg + "3"\n')
d = {}
exec(source, d)
cls = type(name, (VeryImportantSuperClass,), d)
d[name] = cls
return cls
if __name__ == '__main__':
cls = createSubclassAttempt1('Foo')
inst = cls('foo')
print(cls('foo').foo) # prints "foo3"
(Works in both Python 2.7.3 & 3.3)