Dynamically attaching a method to an existing Python object generated with swig?

后端 未结 5 1070
余生分开走
余生分开走 2020-12-03 06:08

I am working with a Python class, and I don\'t have write access to its declaration. How can I attach a custom method (such as __str__) to the

5条回答
  •  春和景丽
    2020-12-03 06:43

    If you create a wrapper class, this will work with any other class, either built-in or not. This is called "containment and delegation", and it is a common alternative to inheritance:

    class SuperDuperWrapper(object):
        def __init__(self, origobj):
            self.myobj = origobj
        def __str__(self):
            return "SUPER DUPER " + str(self.myobj)
        def __getattr__(self,attr):
            return getattr(self.myobj, attr)
    

    The __getattr__ method will delegate all undefined attribute requests on your SuperDuperWrapper object to the contained myobj object. In fact, given Python's dynamic typing, you could use this class to SuperDuper'ly wrap just about anything:

    s = "hey ho!"
    sds = SuperDuperWrapper(s)
    print sds
    
    i = 100
    sdi = SuperDuperWrapper(i)
    print sdi
    

    Prints:

    SUPER DUPER hey ho!
    SUPER DUPER 100
    

    In your case, you would take the returned object from the function you cannot modify, and wrap it in your own SuperDuperWrapper, but you could still otherwise access it just as if it were the base object.

    print sds.split()
    ['hey', 'ho!']
    

提交回复
热议问题