2

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?

2 Answers 2

5

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

2 Comments

I am getting the error TypeError: unbound method myValue() must be called with myAppClass instance as first argument (got nothing instead). What may be the cause as when I try myAppObj().myValue() it works.
Solved it by using myAppObj=type("myAppClass", (object,),myAppObjDict)()
2

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 :)

1 Comment

I think I had it could not be that easy moment while thinking about it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.