简体   繁体   中英

Reducing the number of parameters a function takes in python

I have the following structure in my code:

#!/usr/bin/env python
import <something>
.
.
.
from modules import *
from optparse import OptionParser

class Main:
    def __init__(self):
        parser = self.get_argument()
        self.set_argument(parser)

    def my_args(self):
        parser = OptionParser(usage='usage: %prog [options]', version='%prog 1.0.0')
        parser.add_option('-t', '--test', action='store_true', dest='test', default=False,
            help='Help of test.')
        .
        .
        .
        return parser

    def set_args(self, parser)
        options, args = parser.parse_args()
        params = dict(test=options.test, ..., arg100=options.arg100)
        self.start(**params)

    def start(self, **params):
        print params


    def ...:
        ...
    .
    .
    .

if __name__ == '__main__':
    Main()

I want to run start for getting parameters and its values for using in other functions. but:

TypeError: start() takes exactly 2 arguments (1 given)

How can I use kwargs for passing them?

What is best way in order to use parameters in start . I am really new with kwargs .

**kwargs allows a function to take keywords arguments, and constructs a dictionary

In [3]: def g(**kw):
...:     print(kw)
...:     

In [4]: g(a=1, b=2, c=3)
 {'a': 1, 'c': 3, 'b': 2}

If you want to pass a dictionary to the function, you'll need to unpack the dictionary, like this:

In [5]: d = dict(e=42, f=65)

In [6]: g(**d)
   {'e': 42, 'f': 65}

See http://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ , or the official documentation

The following works for me:

class Test(object):

    def a(self):
        p = {"a":1, "b":2}
        self.start(**p)

    def start(self, **params):
        print(params)


t = Test()
t.a()

result is:

{'a': 1, 'b': 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM