簡體   English   中英

如何在python中動態創建對象?

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

如何在 Python 中動態創建對象? 我經常想將信息傳遞給我的 Django 模板,其格式如下:

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

這使模板看起來不整潔。 所以我認為最好只創建一個像這樣的對象:

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

所以我可以這樣做:

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

而不是調用字典。

由於我只需要該對象一次,是否可以在不先編寫類的情況下創建它? 有沒有簡寫代碼? 這樣做可以嗎,還是 Python 不好?

您可以使用內置類型函數

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

但是在這種特定情況下(Django 模板的數據對象),您應該使用@Xion 的解決方案。

在 Django 模板中,點符號 ( testobj.test ) 可以解析為 Python 的[]運算符。 這意味着您只需要一個普通的字典:

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

將它作為testobj變量傳遞給您的模板,您可以在模板中自由使用{{ testobj.test }}和類似的表達式。 它們將被轉換為testobj['test'] 這里不需要專門的課程。

Python 3.3+ types.SimpleNamespace還有另一種解決方案

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

test_obj.a
test_obj.b()

使用構建函數類型:文檔

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

第一個和第二個 X 相同

這是創建對象的一種流氓、極簡的方式。 類是一個對象,因此只需將類定義語法當作 Python對象字面量即可

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

類變量是對象的成員,很容易被引用:

assert testobj.test3 == 1

這很奇怪,一個從未用作類的類:它從未實例化。 但它是一種創建臨時單例對象的簡潔方法:類本身就是您的對象。

為了完整起見,還有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']

如果你只需要一個“QuickRecord”,你可以簡單地聲明一個空類
你可以使用它而不必實例化一個對象......
(抓住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 )

下面的代碼還需要創建一個類,但它更短:

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