How to create objects on the fly in python?

前端 未结 8 2218
野的像风
野的像风 2020-12-17 09:34

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],          


        
8条回答
  •  粉色の甜心
    2020-12-17 10:08

    Here's a rogue, minimalist way to create an object. A class is an object, so just commandeer the class definition syntax as if it were a Python object literal:

    class testobj(object):
        test = [a1,a2,b2]
        test2 = 'something else'
        test3 = 1
    

    Class variables are the members of the object, and are easily referenced:

    assert testobj.test3 == 1
    

    This is weird, a class never used as a class: it's never instantiated. But it's a low-clutter way to make an ad hoc, singleton object: The class itself is your object.

提交回复
热议问题