Search code examples
pythoncode-conversion

Python wrapper class


I've been exposed to python for about 2 years and I have never used or come across a wrapper class until today when I see something like this:

class Wrapper(object):
  def list_to_str(self, my_list):
    if self.mode == 'convert':
      return str(my_list)

  def get_tree(self, my_list)
      my_tree = self.list_to_tree(my_tree)
     return my_tree

class RealClass(Wrapper):

  def __init__(self, mode):
    self.mode = mode
  
  def list_to_tree(self, list):
       ""convert list to tree""
       return tree

I was quite annoyed by this code and personally find it really ugly.

However, because I have not been exposed to wrapper class in production environment (or any other environment) I'm not sure if the above practice is find.

Please tell me if the ^ is OK, and if not, please tell me how should I re-factor these 2 classes (completely remove wrapper?) or provide me some resources.

So far I looked at the python documentation and some other posts related to the wrapper class, but it seems that all the _ getattribute _ and stuff like that doesn't really apply here.


Solution

  • The problem is that your example isn't a wrapper class at all. It could either be viewed as an abstract base class or as a mix-in. In either case, the idea is to have a class that implements some functionality but isn't intended to stand on its own. Its common for these types of classes to skip initialization and just assume that a real implementing class sets up the object properly.

    Generally, classes aren't required to have an __init__ but its very useful for setting up instance variables and so most classes have them.

    In your case, the mis-named Wrapper assumes that an implementor will define self.mode and self.list_to_tree. If that contract is satisfied, it does list_to_str and get_tree for you. There could be multiple implementors who have different views of what mode and list_to_tree are, but they would all get the same functionality from the base class.