How to avoid excessive parameter passing?

后端 未结 6 851
予麋鹿
予麋鹿 2021-02-11 00:22

I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These opt

6条回答
  •  天涯浪人
    2021-02-11 00:52

    Maybe you should organize your code more into classes and objects? As I was writing this, Jimmy showed a class-instance based answer, so here is a pure class-based answer. This would be most useful if you only ever wanted a single behavior; if there is any chance at all you might want different defaults some of the time, you should use ordinary object-oriented programming in Python, i.e. pass around class instances with the property p set in the instance, not the class.

    class Aclass(object):
        p = None
        @classmethod
        def init_p(cls, value):
            p = value
        @classmethod
        def meth1(cls):
            # some code
            res = cls.meth2()
            # some more code w/ res
        @classmethod
        def meth2(cls):
            # do something with p
            pass
    
    from a import Aclass as ac
    
    ac.init_p(some_command_line_argument_value)
    
    ac.meth1()
    ac.meth2()
    

提交回复
热议问题