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?
source share