简体   繁体   English

如何在python中动态创建对象?

[英]How to create objects on the fly in python?

How do I create objects on the fly in Python?如何在 Python 中动态创建对象? I often want to pass information to my Django templates which is formatted like this:我经常想将信息传递给我的 Django 模板,其格式如下:

{'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?这样做可以吗,还是 Python 不好?

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.但是在这种特定情况下(Django 模板的数据对象),您应该使用@Xion 的解决方案。

In Django templates, the dot notation ( testobj.test ) can resolve to the Python's [] operator.在 Django 模板中,点符号 ( testobj.test ) 可以解析为 Python 的[]运算符。 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.将它作为testobj变量传递给您的模板,您可以在模板中自由使用{{ testobj.test }}和类似的表达式。 They will be translated to testobj['test'] .它们将被转换为testobj['test'] No dedicated class is needed here.这里不需要专门的课程。

There is another solution in Python 3.3+ types.SimpleNamespace Python 3.3+ types.SimpleNamespace还有另一种解决方案

from types import SimpleNamespace
test_obj = SimpleNamespace(a=1, b=lambda: {'hello': 42})

test_obj.a
test_obj.b()

use building function type: document使用构建函数类型:文档

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

first and second X are identical第一个和第二个 X 相同

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 :类是一个对象,因此只需将类定义语法当作 Python对象字面量即可

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.但它是一种创建临时单例对象的简洁方法:类本身就是您的对象。

for the sake of completeness, there is also recordclass :为了完整起见,还有recordclass

from recordclass import recordclass
Test = recordclass('Test', ['test', 'test1', 'test2'])
foo = Test(test=['a1','a2','b2'], test1='someting else', test2=1)

print(foo.test)
.. ['a1', 'a2', 'b2']

if you just need a "QuickRecord" you can simply declare a empty class如果你只需要一个“QuickRecord”,你可以简单地声明一个空类
and you can use it without having to instantiate an object...你可以使用它而不必实例化一个对象......
(just seize the dynamic features of python language... "á la Javascript") (抓住python语言的动态特性...“á la Javascript”)

# create an empty class...
class c1:pass

# then just add/change fields at your will
c1.a = "a-field"
c1.b = 1
c1.b += 10
print( c1.a, " -> ", c1.b )

# this has even the 'benesse' of easealy taking a 
# snapshot whenever you want

c2 = c1()
print( c2.a, " -> ", c2.b )

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM