2016-07-15 42 views
0

我正尝试编写Python 2.7的cod,通过在需求更改的情况下提供默认值的同时删除参数顺序来进行扩展。这里是我的代码:在Python中同时删除参数顺序并提供默认值的最安全的方法

# Class: 
class Mailer(object): 
    def __init__(self, **args): 
     self.subject=args.get('subject', None) 
     self.mailing_list=args.get('mailing_list', None) 
     self.from_address=args.get('from_address', None) 
     self.password=args.get('password', None) 
     self.sector=args.get('sector', "There is a problem with the HTML") 
# call: 
mailer=Mailer(
    subject="Subject goes here", 
    password="password", 
    mailing_list=("[email protected]", "[email protected]","[email protected]"), 
    mailing_list=("[email protected]", "[email protected]"), 
    from_address="[email protected]", 
    sector=Sector() 

我还是新的语言,所以,如果有更好的方式来做到这一点,我真的很想知道。提前致谢。

回答

0

尝试初始化类是这样的:

class Mailer(object): 
    def __init__(self, **args): 
     for k in args: 
      self.__dict__[k] = args[k] 
0

与你做它的方式的问题是,有没有什么参数的类可以接受的文件,所以help(Mailer)是没用的。你应该做的是在可能的情况下在__init__()方法中提供默认参数值。

要将参数设置为实例上的参数,可以使用一些自省功能(如another answer I wrote),以避免所有锅炉位置self.foo = foo的东西。

class Mailer(object): 
    def __init__(self, subject="None", mailing_list=(), 
       from_address="[email protected]", password="hunter42", 
       sector="There is a problem with the HTML"): 

    # set all arguments as attributes of this instance 
    code  = self.__init__.__func__.func_code 
    argnames = code.co_varnames[1:code.co_argcount] 
    locs  = locals() 
    self.__dict__.update((name, locs[name]) for name in argnames) 

您可以提供参数以任意顺序,如果用显式的参数名称通话,不论他们如何定义的方法,所以你的例子电话仍然可以工作。

相关问题