0

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...

6
  • 1
    WHat are you trying to accomplish? Commented Jan 10, 2013 at 8:44
  • Does it need to be of a specific name? You could just generate it then assign it to whatever variable like NewClassName = OldClassName or ClassName = ClassFactory(**options). The only "downside" is that repring it will give the original name. Commented Jan 10, 2013 at 8:46
  • You can create classes dynamically based on input parameters, is that what you are trying to do? Commented Jan 10, 2013 at 8:46
  • If you just want to create class in function, type() will be your friend. If you want others, please declare more details. Commented Jan 10, 2013 at 8:47
  • Why do you need a class created at runtime. That's very unusual that you have a real usecase for that. Commented Jan 10, 2013 at 9:35

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

9 Comments

MyType not define after create this by namedtuple. Any idea?
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.
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.
Thank you @Thorsten Kranz. But I do my work with the other snippet.
I got the same error, try changing MyTuple to MyType; that fixes it.
|
2

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.