0

我有一个函数,它的工作是根据传递函数的给定名称隐式生成一个 python 类。之后,我也想为生成的类隐式创建字段和方法。我不知道如何启动它。有人可以帮忙吗...

4

2 回答 2

3

你真的需要上课吗?对于在运行时创建的“类型”,也许 namedtuple 将是一个解决方案。

from collections import namedtuple
MyType= namedtuple("MyType", "field1 method1")
x = MyType(field1="3", method1=lambda x: x+1)
print x.field1, x.method1(3)
于 2013-01-10T08:48:52.100 回答
2

您可以尝试使用以下方法type()

def my_func(self):
    return 'my_func to become my_method!'

def class_maker(name,**kwargs):
    return type(name, (object,), kwargs)

A = class_maker('MyClass',my_method=my_func, field='this is my_field!')
inst = A()

print inst.my_method()
print inst.field
print inst
print A

输出:

my_func to become my_method!
this is my_field!
<__main__.MyClass object at 0x962902c>
<class '__main__.MyClass'>
于 2013-01-10T08:46:33.140 回答