Python Design: OOP

I am trying to do something in this direction:

class A: def __init__( self, x=None, y=None ): self.x = x self.y = y class B( A ): def do_something_in_Bs_context( self ): print "In B" class C( A ): def do_something_in_Cs_context( self ): print "In C" a = A(1,2) b = B.do_something_in_Bs_context( a ) c = C.do_something_in_Cs_context( a ) 

As expected, this code will generate this error:

 TypeError: unbound method do_something_in_Bs_context() must be called with B instance as first argument (got A instance instead) 

The main reason for this design is that A is a container of data (say, tables), and B and C are a set of operations on A. Both B and C work with the same data, but conceptually represent a separate set of operations that can be performed on the same data. I could combine all the operations in B and C inside A, but I want to create a separation in concepts. (As an example, on a table, I can perform various sets of operations that can be grouped into the expression โ€œCalculus or trignometry.โ€ Thus, A: Table, B: Calculus, C: Trignometry)

This reminded me of the Model-View-Controller paradigm with a slight twist.

I came up with the following solutions:

  • B and C are implemented as conceptually different classes (a View / Controller) that support a reference to instance A and work on this instance.
  • Since B and C simply combine the methods on A together, create modules with functions that work on instance A.

I don't like any of these solutions a lot (2 is slightly better than 1), but then I'm not sure if there is a better / cleaner / more pythonic way to solve this problem. Any pointers?

+4
source share
2 answers

This is how I understand the question: B and C are collections of functions that consume type A data. What you want to do logically groups the functions.

I suggest doing one of the following:

  • divides functions into classes B and C that work with A - this is the HAS-A relationship. Functions / methods can be static if you need it
  • divides functions into modules B and C , creating top-level function definitions

I think inheritance would be a bad solution to this problem. I do not think there is an IS-A relationship.

+6
source

Move the state to an additional class and make the instance its attribute A:

 class State(object): def __init__( self, x=None, y=None ): self.x = x self.y = y class A(object): def __init__( self, state=None ): self.state = state class B( A ): def __init__( self, state=None ): super(B, self).__init__(state) def do_something_in_Bs_context( self ): print self.state.x class C( A ): def __init__( self, state=None ): super(C, self).__init__(state) def do_something_in_Cs_context( self ): print self.state.y s = State(1, 2) b = B(s) c = C(s) b.do_something_in_Bs_context() c.do_something_in_Cs_context() 
+1
source

All Articles