Let a class behave like it's a list in Python

前端 未结 4 1396
太阳男子
太阳男子 2020-12-08 18:39

I have a class which is essentially a collection/list of things. But I want to add some extra functions to this list. What I would like, is the following:

  • I h
4条回答
  •  Happy的楠姐
    2020-12-08 19:15

    If you don't want to redefine every method of list, I suggest you the following approach:

    class MyList:
      def __init__(self, list_):
        self.li = list_
      def __getattr__(self, method):
        return getattr(self.li, method)
    

    This would make methods like append, extend and so on, work out of the box. Beware, however, that magic methods (e.g. __len__, __getitem__ etc.) are not going to work in this case, so you should at least redeclare them like this:

    class MyList:
      def __init__(self, list_):
        self.li = list_
      def __getattr__(self, method):
        return getattr(self.li, method)
      def __len__(self):
        return len(self.li)
      def __getitem__(self, item):
        return self.li[item]
      def fancyPrint(self):
        # do whatever you want...
    

    Please note, that in this case if you want to override a method of list (extend, for instance), you can just declare your own so that the call won't pass through the __getattr__ method. For instance:

    class MyList:
      def __init__(self, list_):
        self.li = list_
      def __getattr__(self, method):
        return getattr(self.li, method)
      def __len__(self):
        return len(self.li)
      def __getitem__(self, item):
        return self.li[item]
      def fancyPrint(self):
        # do whatever you want...
      def extend(self, list_):
        # your own version of extend
    

提交回复
热议问题