1

Let's say I have two classes A and B, both class needs to maintain fairly complex internal states, and the behavior changes with command line arguments provided:

           ARGS = [arg1, arg2, arg3]
               /                 \
              /                   \ 
         class A:                class B

            def __init__(self, key1=arg1, key2=arg2 ...)
                  self.state1 = blah ...
                  self.state2 = blah ...

I have two questions:

(1) I could initialize object with different behavior through key=val argument list, but this long list soon become clumsy. I could also change state directly, is there any rationales or rules I should follow here?

(2) Since both class A and B needs access to command line options as well as other switches, for now, there is a global G:

 class G:
      self.opt1 = True
      self.opt2 = False
      ...

which essentially maintain the shared state and accessible to all parties of interests? Is this a acceptable design or something to be frowned upon? TIA

python152
  • 1,811
  • 2
  • 15
  • 18

1 Answers1

0
  1. You could write an initializer that uses kwargs. That way you can set as many or as few attributes as you want in the initializer. This post might help. I think it depends on whether you always want to set all of the properties of A and B when you instantiate them. Properties that you always want to set are good to have as arguments to the initializers to enforce that you do actually set them. But if there are properties you only set sometimes (like some sort of optional flag with a default value), it probably makes more sense to set them using better to set them directly after instantiating the object.

  2. This is a perfectly OK solution I think. It's certainly better to have the global options put together in an object, instead of having them just as global variables. Another option would be to pass the global options to A and B as part of the initializers, so only the part of the program that instantiated A and B would need to know directly about the global state. After that, A and B would have local attributes to check. This approach would not be as good as your G class if you expect the global state to change. I think the way that I would do this is to make the global state options static properties of G so that you don't need to pass around any instances of G and can just access the properties through the class

I think these are good design questions, and you've identified some key tradeoffs. Feel free to disagree with me :)

Community
  • 1
  • 1
ezig
  • 1,219
  • 1
  • 10
  • 15