Reputation: 1
Suppose there is a class defining a few standard functions where one of them is a function to initiate a command. Here 2 examples:
Ser.Cmd(CmdEnum.MoveAbsolute,10,20,'Ack')
Ser.Cmd(CmdEnum.MoveRelative,5,0,'Ack')
where CmdEnum.MoveAbsolute and CmdEnum.MoveRelative are enumerate values for the specific command to execute.
In this class there are also other "generic" functions such as Ser.enable or Ser.getstatus.
The usability of the class would be more clean if the syntax of the command could change into:
Ser.MoveAbsolute(10,20,'Ack')
Is it possible to create functions in this style by passing an enum type during object creation?
Can someone give an example?
The idea is to not have the part ".MoveAbsolute" hard coded in the class, but being specified based on the enumerate value that is passed.
Upvotes: 0
Views: 128
Reputation: 5589
You can use the functools.partial
function for this.
import functools
class MySer(Ser):
def __init__(self):
self.MoveAbsolute = functools.partial(self.Cmd, CmdEnum.MoveAbsolute)
self.MoveRelative = functools.partial(self.Cmd, CmdEnum.MoveRelative)
You can now call your functions like this:
ser = MySer()
ser.MoveAbsolute(10, 20, 'Ack')
Upvotes: 1
Reputation: 39414
You don't need enums as you can indicate the functions directly:
So instead of:
Ser.Cmd(CmdEnum.MoveAbsolute,10,20,'Ack')
Ser.Cmd(CmdEnum.MoveRelative,5,0,'Ack')
which might call:
Ser.MoveAbsolute(10,20,'Ack')
you can write:
Ser.Cmd(Ser.MoveAbsolute,10,20,'Ack')
but the implementation of Cmd
would be:
def Cmd(self, func, *args):
func(*args)
Upvotes: 0