Reputation: 7476
I have the following code ... and I have several more like this (&,|,^,) the only difference is the method name __method__
as you can see.
Is there a way to to have a separate method that get as parameter the method name and construct a call , so I have just a redirect call in every "override".
def __add__(self, rhs) :
assert self.sdp[:LSDP.LVLBITS] == rhs.sdp[:LSDP.LVLBITS], "add: operands must be at the same level"
return (self.sdp[:LSDP.LVLBITS]).cat( self.sdp[LSDP.LVLBITS:].__add__(rhs.sdp[LSDP.LVLBITS:]) )
def __mul__(self, rhs) :
assert self.sdp[:LSDP.LVLBITS] == rhs.sdp[:LSDP.LVLBITS], "mul: operands must be at the same level"
return (self.sdp[:LSDP.LVLBITS]).cat( self.sdp[LSDP.LVLBITS:].__mul__(rhs.sdp[LSDP.LVLBITS:]) )
Upvotes: 2
Views: 41
Reputation: 32244
You could use the operator module, have a common method that takes the operation to call and the right hand side
def _run_operator(self, op, rhs):
assert self.sdp[:LSDP.LVLBITS] == rhs.sdp[:LSDP.LVLBITS], f"{op.__name__}: operands must be at the same level"
return (self.sdp[:LSDP.LVLBITS]).cat(op(self.sdp[LSDP.LVLBITS:], rhs.sdp[LSDP.LVLBITS:]))
def __add__(self, rhs):
return self._run_operator(operator.add, rhs)
def __mul__(self, rhs):
return self._run_operator(operator.mul, rhs)
Upvotes: 2