if I have something like
import mynewclass
Can I add some method to mynewclass? Something like the following in concept:
def newmethod(self,x):
return x + self.y
mynewclass.newmethod = newmethod
(I am using CPython 2.6)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Python the import statement is used for modules, not classes… so to import a class you need something like
More to the point of your question the answer is yes. In Python classes are just regular objects and a class method is just a function stored in an object attribute.
Attributes of object instances in Python moreover are dynamic (you can add new object attributes at runtime) and this fact, combined with the previous one means that you can add a new method to a class at runtime.
How can this work? When you type
Python will do the following:
look for
new_methodinside the objectobj.Not finding it as an instance attribute it will try looking inside the class object (that is available as
obj.__class__) where it will find the function.Now there is a bit of trickery because Python will notice that what it found is a function and therefore will "wrap" it in a closure to create what is called a "bound method". This is needed because when you call
obj.new_method()you want to callMyClass.new_method(obj)… in other words binding the function toobjto create the bound method is what takes care of adding theselfparameter.This bound method is what is returned by
obj.new_method, and then this will be finally called because of the ending()on that line of code.If the search for the class also doesn’t succeed instead parent classes are also all searched in a specific order to find inherited methods and attributes and therefore things are just a little bit more complex.