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

后端 未结 5 1087
余生分开走
余生分开走 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:32

    >>> class C(object):
    ...     pass
    ... 
    >>> def spam(self):
    ...     return 'spam'
    ... 
    >>> C.__str__ = spam
    >>> print C()
    spam
    

    It won't work on classes which use __slots__.

提交回复
热议问题