I have a function that its job is generate a python class implicitly according to the given name that pass throw the function. After that I want to create field and method implicitly for the generated class too. I don't know how can start it. Can someone help...
2 Answers
Do you really need a class? For "types" created at runtime, maybe namedtuple would be a solution.
from collections import namedtuple
MyType= namedtuple("MyType", "field1 method1")
x = MyType(field1="3", method1=lambda x: x+1)
print x.field1, x.method1(3)
9 Comments
Thorsten Kranz
mmm, my code works on my box. Do you use exactly my code? If not, please show me your code so I can look for errors.
Thorsten Kranz
For me, the output is
3 4, also on Python 2.7. Could anybody else please verify it works? So we could concentrate on why it fails on your system.root
I got the same error, try changing
MyTuple to MyType; that fixes it. |
You can try something like this using 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
Outputs:
my_func to become my_method!
this is my_field!
<__main__.MyClass object at 0x962902c>
<class '__main__.MyClass'>
NewClassName = OldClassNameorClassName = ClassFactory(**options). The only "downside" is thatrepring it will give the original name.type()will be your friend. If you want others, please declare more details.