2016-07-15 46 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) 

您可以提供參數以任意順序,如果用顯式的參數名稱通話,不論他們如何定義的方法,所以你的例子電話仍然可以工作。

相關問題