Rohit Srivastava
Rohit Srivastava

Reputation: 278

Adding methods in type() generated objects in python

I am generating objects using type for using some of the code that is previously written

# Assume that myAppObjDict is already initialized.
myAppObj=type("myAppClass", (object,),myAppObjDict)

Now I want to add a method say myValue()in it so that if I should be able to call

value=myAppObj.myValue() 

What should be the approach?

Upvotes: 2

Views: 71

Answers (2)

Ber
Ber

Reputation: 41873

You should be able to assign any function to the class after creation:

def method(self):
    print self.__class__.__name__


def my_class (object):
    pass


my_class.method = method

o = my_class()
o.method()

You can do this assignment at any time, and all object will have the new method added, event those already created.

After all, Python is a dynamic language :)

Upvotes: 2

Duncan
Duncan

Reputation: 95722

You should add the methods to myAppObjDict before you create the class:

def myValue(self, whatever):
    pass
myAppObjDict['myValue'] = myValue

# Assume that myAppObjDict is already initialized.
myAppObj=type("myAppClass", (object,),myAppObjDict)

Alternatively define a base class containing the methods and include it in your tuple of base classes.

class MyBase(object):
    def myValue(self): return 42

# Assume that myAppObjDict is already initialized.
myAppObj=type("myAppClass", (MyBase,),myAppObjDict)

Upvotes: 5

Related Questions