0

I have a situation like below

class MyViewStorage(Object):
      # methods

class MyView1(FormView):
      # methods

class MyView2(FormView):
      # methods

MyViewStorage provides some methods to handle storage in MyView1 and MyView2. These methods require instance attributes created in MyView1 and MyView2.

There are two approaches I have now to use this class.

  1. To inherit MyViewStorage in other two classes something as MyView1(FormView, MyViewStorage). Then process methods by simply using instance attributes created in other two classes.

  2. To create an instance of MyViewStorage by first creating initial instance arguments in MyView1 and MyView2 classes

as shown below

def __init__(self, obj, user, form):
    self.obj = obj
    self.user = user
    self.form = form

Which one is preferred approach?

Iamcool
  • 1,387
  • 2
  • 12
  • 24

1 Answers1

1

That Depends on What Kind of Usage you see for MyViewStorage now and in Future.

A. If you know that MyViewStorage will only be used in views like MyView1 and MyView2 and nowhere else. Then it makes a lot of sense that you transfer all common code, present in MyView1 and MyView2 related to storage, in MyViewStorage itself and inherit from it.

PS: You must know how multiple inheritance work in Python, It prioritizes the attributes from left to right in Parent classes (i.e if left most class has the required attribute then it is picked)

B. If you think that MyViewStorage class should be a generic one or can have a lot of extra functionality, which can be used anywhere and can be changed from time to time to make it more generic, then it makes sense to create an instance and use it (because you won't want un-neccessary attributes in your Views which are not useful to you)

Hope this helps

Sahil kalra
  • 8,344
  • 4
  • 23
  • 29
  • If you choose the second, I would even just create a util file and add your logic as functions outside of classes if it makes sense to do so. – Ian Kirkpatrick Jul 27 '17 at 17:01