Dimitri Danilov Dimitri Danilov - 5 months ago 34
Python Question

Why isn't my monkey patching isn't working ?

I am trying to add a method to a class that I import.

This is my code :

from pyrser.parsing import node

def to_dxml(self):
return "test"

node.Node().to_dxml = to_dxml

tree = node.Node()
tree.ls = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]]
tree.dct = {"g":1, "y":2, "koko":{'D', 'T', 'C'}}
tree.aset = {'Z', 'X', 'T', 'U'}
tree.ablob = b'\xFF\xaa\x06Th -}'

But when I run it I get

AttributeError: 'Node' object has no attribute 'to_dxml'

Any idea why it isn't working ?


You need to add attribute to the class, not object.

node.Node().to_dxml = to_dxml

Should be

node.Node.to_dxml = to_dxml