How to create objects on the fly in python?

前端 未结 8 2190
野的像风
野的像风 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:05

    Use collections.namedtuple.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 10:10

    There is another solution in Python 3.3+ types.SimpleNamespace

    from types import SimpleNamespace
    test_obj = SimpleNamespace(a=1, b=lambda: {'hello': 42})
    
    test_obj.a
    test_obj.b()
    
    0 讨论(0)
  • 2020-12-17 10:11

    use building function type: document

    >>> class X:
    ...     a = 1
    ...
    >>> X = type('X', (object,), dict(a=1))
    

    first and second X are identical

    0 讨论(0)
  • 2020-12-17 10:21

    In Django templates, the dot notation (testobj.test) can resolve to the Python's [] operator. This means that all you need is an ordinary dict:

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

    Pass it as testobj variable to your template and you can freely use {{ testobj.test }} and similar expressions inside your template. They will be translated to testobj['test']. No dedicated class is needed here.

    0 讨论(0)
  • 2020-12-17 10:24

    The code below also require a class to be created however it is shorter:

     >>>d = {'test':['a1','a2','b2'], 'test2':'something else', 'test3':1}
     >>> class Test(object):
     ...  def __init__(self):
     ...   self.__dict__.update(d)
     >>> a = Test()
     >>> a.test
     ['a1', 'a2', 'b2']
     >>> a.test2
     'something else'
    
    0 讨论(0)
提交回复
热议问题