在 Python 中同时删除参数顺序和提供默认值的最安全方法



我正在尝试编写Python 2.7编码,通过删除参数顺序更容易扩展,同时在需求发生变化的情况下提供默认值。这是我的代码:

# 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@email.com", "email@email.com","email@email.com"),
    mailing_list=("email@email.com", "email@email.com"),
    from_address="email@email.com",
    sector=Sector()

我对这门语言还很陌生,所以如果有更好的方法来实现这一目标,我真的很想知道。提前谢谢。

尝试以下方式初始化类:

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

你这样做的方式的问题在于没有关于类接受哪些参数的文档,所以help(Mailer)是无用的。您应该做的是在可能的情况下在 __init__() 方法中提供默认参数值。

要将参数设置为实例上的属性,您可以使用一些内省,就像我写的另一个答案一样,以避免所有样板self.foo = foo东西。

class Mailer(object):
    def __init__(self, subject="None", mailing_list=(),
                 from_address="noreply@example.com", 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)

如果使用显式参数名称进行调用,则可以按任意顺序提供参数,而不管它们在方法中的定义方式如何,因此示例调用仍然有效。

最新更新