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

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

    Create a subclass. Example:

    >>> import datetime
    >>> t = datetime.datetime.now()
    >>> datetime.datetime.__str__ = lambda self: 'spam'
    ...
    TypeError: cant set attributes of built-in/extension type 'datetime.datetime'
    >>> t.__str__ = lambda self: 'spam'
    ...
    AttributeError: 'datetime.datetime' object attribute '__str__' is read-only
    >>> class mydate(datetime.datetime):
        def __str__(self):
            return 'spam'
    
    >>> myt = mydate.now()
    >>> print t
    2009-09-05 13:11:34.600000
    >>> print myt
    spam
    

提交回复
热议问题