开发者

Add an attribute to a class dynamically at runtime in Python

开发者 https://www.devze.com 2023-04-03 23:29 出处:网络
When I do the following: def Welcome(email, temporaryPassword): model = object() model.TemporaryPassword = temporaryPassword

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 (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
0

精彩评论

暂无评论...
验证码 换一张
取 消