Monkey-patch Python class

后端 未结 4 1976
醉酒成梦
醉酒成梦 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条回答
  •  猫巷女王i
    2020-11-27 03:25

    Avoid the from ... import (horrid;-) way to get barenames when what you need most often are qualified names. Once you do things the right Pythonic way:

    import module
    
    class ReplaceClass(object): ...
    
    module.MyClass = ReplaceClass
    

    This way, you're monkeypatching the module object, which is what you need and will work when that module is used for others. With the from ... form, you just don't have the module object (one way to look at the glaring defect of most people's use of from ...) and so you're obviously worse off;-);

    The one way in which I recommend using the from statement is to import a module from within a package:

    from some.package.here import amodule
    

    so you're still getting the module object and will use qualified names for all the names in that module.

提交回复
热议问题