根据要求,这适用于 Python 2.7 和 Python 3.4,打印3
:
def makeClass(x):
exec('class %s:\n\tdef __init__(self,v):\n\t\tself.value = v' % x)
return eval('%s' % x)
myClass = makeClass('Int')
myInt = myClass(3)
print(myInt.value)
如果您希望从现有类中添加方法:
def makeClass(name):
parent = name.lower()
exec('class %s(%s):\n\tdef __init__(self,v):\n\t\tself.value = v' % (name, parent))
return eval('%s' % name)
Int = makeClass('Int')
myInt = Int(3)
Str = makeClass('Str')
myStr = Str(3)
print(myInt.value, myInt == 3, myInt == 5)
print(myStr.value, myStr == '3', myStr == 3)
输出:
3 True False
3 True False
少打字有副作用:
def makeClass(name):
parent = name.lower()
exec('global %s\nclass %s(%s):\n\tdef __init__(self,v):\n\t\tself.value = v' % (name, name, parent))
makeClass('Int')
myInt = Int(3)
makeClass('Str')
myStr = Str(3)
不过, Mgilson 的type
答案可能是首选。