I am trying to define in python a class B, subclass of A, that could accept multiple ways of being instantiated to be very flexible. A is a simple class with few members. I know how to write A to allow a mix of positional/keywords arguments and having default values if some arguments are omitted.
My problem comes with class B. B is simply A with an extra member. But when I create an instance of B, I would like to have the choice between:
- an instance created from a mix of positional/keyword arguments (pretty much like A)
- an instance created specifying the extra member and an existing instance (or a copy) of A
- created using only an existing instance of A and the extra member gets a default value.
- making mutually exclusive the use of an existing instance of A and positional/keywords arguments
edit: something like this
class A:
def __init__(self, x1=1, x2='a', x3=4.0)
self.x1=x1
self.x2=x2
self.x3=x3
class B(A):
def __init__(self, x1=1, x2='a', x3=4.0, x4='t')
self.x4=x4
A.__init__(x1,x2,x3)
but then I would like to use it like this:
a1=A()
b1=B() # takes all defaults
b2=B(x4='r') # x1,x2,x3 gets defaults from A
b3=B(a1,x4='z') # use a1, an instance of A
b4=B(x1,x2,x3,x4) # defines manually all arguments
b5=B(a1,x1=2) # this one should not work because x1 can come from the instance a1 or x1
The simplest thing is probably to define
Bwith a nice straightforward initialiser with the same signature asAuses and then additional factory functions defined as class methods to do the more complicated scenarios. That way you won’t get messed up when two different methods of construction actually take exactly indistinguishable arguments.So something like: