Python how to override a method defined in a module of a third party library

前端 未结 1 594
無奈伤痛
無奈伤痛 2020-12-17 16:35

I\'ve installed a third party library tornado by pip and need to override a method, say to_unicode defined in the global scope

相关标签:
1条回答
  • 2020-12-17 17:13

    You can simply rebind the name of an object (in this case, a module-level function) to a different object. For example, if you want to have math.cos work with degrees instead of radians, you could do

    >>> import math
    >>> math.cos(90)
    -0.4480736161291701
    >>> old_cos = math.cos
    >>> def new_cos(degrees):
    ...     return old_cos(math.radians(degrees))
    ...
    >>> math.cos = new_cos
    >>> math.cos(90)
    6.123233995736766e-17
    

    However, that might cause problems to other functions that use that module...

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