Monkey-patch Python class

后端 未结 4 1974
醉酒成梦
醉酒成梦 2020-11-27 03:11

I\'ve got a class, located in a separate module, which I can\'t change.

from module import MyClass

class ReplaceClass(object)
  ...

MyClass = ReplaceClass
         


        
4条回答
  •  没有蜡笔的小新
    2020-11-27 03:34

    I am but an egg . . . . Perhaps it is obvious to not-newbies, but I needed the from some.package.module import module idiom.

    I had to modify one method of GenerallyHelpfulClass. This failed:

    import some.package.module
    
    class SpeciallyHelpfulClass(some.package.module.GenerallyHelpfulClass): 
        def general_method(self):...
    
    some.package.module.GenerallyHelpfulClass = SpeciallyHelpfulClass
    

    The code ran, but didn't use the behaviors overloaded onto SpeciallyHelpfulClass.

    This worked:

    from some.package import module
    
    class SpeciallyHelpfulClass(module.GenerallyHelpfulClass): 
        def general_method(self):...
    
    module.GenerallyHelpfulClass = SpeciallyHelpfulClass
    

    I speculate that the from ... import idiom 'gets the module', as Alex wrote, as it will be picked up by other modules in the package. Speculating further, the longer dotted reference seems to bring the module into the namespace with the import by long dotted reference, but doesn't change the module used by other namespaces. Thus changes to the import module would only appear in the name space where they were made. It's as if there were two copies of the same module, each available under slightly different references.

提交回复
热议问题