2011-09-12 136 views
1

當我做到以下幾點:在運行時動態的屬性添加一個類在Python

def Welcome(email, temporaryPassword): 
    model = object() 
    model.TemporaryPassword = temporaryPassword 
    model.Email = email 

我得到一個錯誤:

AttributeError: 'object' object has no attribute 'TemporaryPassword' 

如何動態地創建一個對象,就像我現在這樣?

+0

的可能重複[蟒蛇:如何動態地添加屬性類(http://stackoverflow.com/questions/1325673/python-how-to-add-property-to-a -class-動態地) – 2011-09-12 05:09:20

回答

1

使用拉姆達對象:(http://codepad.org/ITFhNrGi

def Welcome(email, temporaryPassword): 
    model = type('lamdbaobject', (object,), {})() 
    model.TemporaryPassword = temporaryPassword 
    model.Email = email 
    return model 


t = Welcome('[email protected]','1234') 
print(str(t.TemporaryPassword)) 
1

可以定義一個虛設類第一:

class MyObject(object): 
    pass 

obj = MyObject() 
obj.TemporaryPassword = temporaryPassword 
1

如果僅使用對象作爲數據結構(即,沒有方法),則可以使用namedtuplecollections package

from collections import namedtuple 
def welcome(email, tmp_passwd): 
    model = namedtuple('MyModel', ['email', 'temporary_password'])(email, tmp_passwd) 
    ... 

順便說一句,如果喲你的welcome函數只創建對象並返回它,不需要它。剛:

from collections import namedtuple 
Welcome = namedtuple('Welcome', ['email', 'temporary_password']) 

ex = Welcome('[email protected]', 'foobar') 
print ex.email 
print ex.temporary_password