在Python中在运行时动态地向类添加属性

时间:2011-09-12 05:05:27

标签: python

当我执行以下操作时:

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

我收到错误:

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

如何动态创建一个像我一样的对象?

3 个答案:

答案 0 :(得分:1)

使用lambda对象:(http://codepad.org/ITFhNrGi

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


t = Welcome('a@b.com','1234')
print(str(t.TemporaryPassword))

答案 1 :(得分:1)

您可以先定义一个虚拟类:

class MyObject(object):
    pass

obj = MyObject()
obj.TemporaryPassword = temporaryPassword

答案 2 :(得分:1)

如果您仅将对象用作数据结构(即无方法),则可以使用collections package中的namedtuple

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('me@example.com', 'foobar')
print ex.email
print ex.temporary_password