1

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?

010110110101
  • 12,347
  • 23
  • 83
  • 149
  • possible duplicate of [python: How to add property to a class dynamically?](http://stackoverflow.com/questions/1325673/python-how-to-add-property-to-a-class-dynamically) –  Sep 12 '11 at 05:09

3 Answers3

1

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))
DhruvPathak
  • 38,316
  • 14
  • 103
  • 164
1

you can define a dummy class first:

class MyObject(object):
    pass

obj = MyObject()
obj.TemporaryPassword = temporaryPassword
HYRY
  • 83,863
  • 22
  • 167
  • 176
1

If you only use the object as a data structure (i.e. 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
Yannick Loiseau
  • 1,314
  • 8
  • 8