if I have something like
import mynewclass
Can I add some method to mynewclass? Something like the following in concept:
de
Yes, if it's a Python type. Except you'd do it on the class, not the module/package.
In Python the import statement is used for modules, not classes... so to import a class you need something like
from mymodule import MyClass
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.
class MyClass:
def __init__(self, x):
self.x = x
...
obj = MyClass(42)
def new_method(self):
print "x attribute is", self.x
MyClass.new_method = new_method
obj.new_method()
How can this work? When you type
obj.new_method()
Python will do the following:
look for new_method
inside the object obj
.
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 call MyClass.new_method(obj)
... in other words binding the function to obj
to create the bound method is what takes care of adding the self
parameter.
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.