Yannick Turgeon wrote:
Hello,
Thanks to reply. My question has been answered but I'm now wondering if I
do this the best way.
In the real situation I'm implementing a protocol. "A" represent a
command. Say "0144AYHR78" (encoded data) means "Add client Joe" and
"0589UAWERT" means "Ship 3 compressors to Joe". What I want to do is to
create a "A" instance which find the command type and parameters and
"mutate" itself to the good command. All command parameters ("Joe" for the
first one and "3,compressor,Joe" for the secondeone) are kept in a sigle
list.So B1 and B2 would define the function "getClient()" and B2 would
define "getQty()" and "getProduct()" and some other command-specific work.
while True:
encoded_data = readEncodedData()
command = A(encoded_data)
type_ = command .getType() # Define in "A"
if type_ == A.ADD:
# Do what I have to do with a "Add" command using the "command"
instance (B1)
elif type_ == A.SHIP:
# Do what I have to do with a "Ship" command using the "command"
instance (B2)
...
Any suggestion to do this in a better way
Here's how I would do it based on the above:
class Ship:
def __init__(self, args):
""" knows how to decode args """
self.quantity = # your code
self.item = # your code
self.client = # your code
def execute(self):
""" do what is necessary for shipment """
class Add:
def __init__(self, args):
""" knows how to decode args """
self.client = # your code
def execute(self):
""" add a client """
commands = {
"0144": Add, # assuming the first 4 chars encode the command
"0589": Ship,
}
def decode(data):
""" separate the command and its arguments,
hopefully possible without having to know
individual commands
"""
return data[:4], data[4:] # may actually be more complicated
while True:
type_, args = decode(readEncodedData())
cmd = commands[type_](args)
cmd.execute()
Ship and Add may or may not share a common base class depending on whether
you can factor out common functionality - e. g. a mixin that knows how
decode the client, but you do not need to artificially introduce a common
base class as a factory for the actual instances. Just make sure that
__init__() takes a single argument and an execute() method taking no
arguments is available.
The client code (the while loop) is independent of the actual command, so
ideally you just have to create a new class for a new command and enter it
into the commands dictionary.
Peter