Extending builtin classes in python

前端 未结 3 584
情歌与酒
情歌与酒 2020-12-13 14:02

How can I extend a builtin class in python? I would like to add a method to the str class.
I\'ve done some searching but all I\'m finding is older posts, I\'m hoping s

3条回答
  •  失恋的感觉
    2020-12-13 14:36

    Assuming that you can not change builtin classes. To simulate a "class reopening" like Ruby in Python3 where __dict__ is an mappingproxy object and not dict object :

    def open(cls):
      def update(extension):
        for k,v in extension.__dict__.items():
          if k != '__dict__':
            setattr(cls,k,v)
        return cls
      return update
    
    
    class A(object):
      def hello(self):
        print('Hello!')
    
    A().hello()   #=> Hello!
    
    #reopen class A
    @open(A)
    class A(object):
      def hello(self):
        print('New hello!')
      def bye(self):
        print('Bye bye')
    
    
    A().hello()   #=> New hello!
    A().bye()     #=> Bye bye
    

    I could also write a decorator function 'open' as well:

    def open(cls):
      def update(extension):
        namespace = dict(cls.__dict__)
        namespace.update(dict(extension.__dict__))
        return type(cls.__name__,cls.__bases__,namespace)
      return update
    

提交回复
热议问题