简体   繁体   中英

Add an attribute to a class dynamically at runtime in Python

When I do the following:

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

I get an error:

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

How do I dynamically create an object like I am doing?

use lambda object : ( 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))

you can define a dummy class first:

class MyObject(object):
    pass

obj = MyObject()
obj.TemporaryPassword = temporaryPassword

If you only use the object as a data structure (ie no methods) you can use a namedtuple from the collections package :

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

By the way, if your welcome function only creates the object and returns it, there is no need for it. Just:

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

ex = Welcome('me@example.com', 'foobar')
print ex.email
print ex.temporary_password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM