add method to loaded class/module in python

后端 未结 2 438
别那么骄傲
别那么骄傲 2021-01-07 21:43

if I have something like

import mynewclass

Can I add some method to mynewclass? Something like the following in concept:

de         


        
相关标签:
2条回答
  • 2021-01-07 21:55

    Yes, if it's a Python type. Except you'd do it on the class, not the module/package.

    0 讨论(0)
  • 2021-01-07 22:09

    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:

    1. look for new_method inside the object obj.

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

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

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

    0 讨论(0)
提交回复
热议问题