Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

django - How to create objects on the fly in python?

How do I create objects on the fly in Python? I often want to pass information to my Django templates which is formatted like this:

{'test': [a1, a2, b2], 'test2': 'something else', 'test3': 1}

which makes the template look untidy. so I think it's better to just create an object which is like:

class testclass():
    self.test = [a1,a2,b2]
    self.test2 = 'someting else'
    self.test3 = 1
testobj = testclass()

so I can do:

{{ testobj.test }}
{{ testobj.test2 }}
{{ testobj.test3 }}

instead of calling the dictionary.

Since I just need that object once, is it possible to create it without writing a class first? Is there any short-hand code? Is it ok to do it like that or is it bad Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use built-in type function:

testobj = type('testclass', (object,), 
                 {'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()

But in this specific case (data object for Django templates), you should use @Xion's solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...