簡體   English   中英

Python 中的參考資料

[英]References in Python

我有一個需要不斷向所有其他用戶發送數據的多播網絡。 這些數據會不斷變化,所以我不希望程序員不得不處理向用戶發送數據包。 因此,我試圖找出如何引用 object 或 Python 中的變量(我是 Python 新手),以便用戶可以修改它並更改多播數據包中發送的內容。

這是我想要的一個例子:

>>> test = "test"
>>> mdc = MulticastDataClient()
>>> mdc.add(test) # added into an internal list that is sent to all users

# here we can see that we are successfully receiving the data
>>> print mdc.receive() 
{'192.168.1.10_0': 'test'}

# now we try to change the value of test
>>> test = "this should change"
>>> print mdc.receive()
{'192.168.1.10_0': 'test'}   # want 'test' to change to -> 'this should change'

任何有關如何解決此問題的幫助將不勝感激。

更新:

我也嘗試過這種方式:

>>> test = [1, "test"]
>>> mdc = MulticastDataClient()
>>> mdc.add(test)
>>> mdc.receive()
{'192.168.1.10_1': 'test'}
>>> test[1] = "change!"
>>> mdc.receive()
{'192.168.1.10_1': 'change!'}

這確實奏效了。 然而,

>>> val = "ftw!"
>>> nextTest = [4, val]
>>> mdc.add(nextTest)
>>> mdc.receive()
{'192.168.1.10_1': 'change!', '192.168.1.10_4': 'ftw!'}
>>> val = "different."
>>> mdc.receive()
{'192.168.1.10_1': 'change!', '192.168.1.10_4': 'ftw!'}

這不起作用。 我需要'ftw'。 變得“不同”。 在這種情況下。 我正在使用字符串進行測試,並且習慣於將字符串作為其他語言的對象? 我只會編輯 object 內部的內容,所以這最終會起作用嗎?

在 python 中,一切都是參考,但字符串不是可變的。 所以test持有對“test”的引用。 如果您分配“這應該改變”來test ,您只需將其更改為另一個參考。 但是您的客戶仍然提到“測試”。 或更短:它在 python 中不起作用; ;-)

一個解決方案可能是將數據放入 object:

data = {'someKey':"test"}
mdc.add(data)

現在您的客戶持有對字典的引用。 如果您像這樣更新字典,您的客戶將看到更改:

data['someKey'] = "this should change"

你不能,不容易。 Python 中的名稱(變量)只是指針的位置。 覆蓋它,您只需將指針替換為另一個指針,即更改僅對使用相同變量的人可見。 Object 成員基本相同,但是由於每個人都可以看到他們的 state 並帶有指向它們的指針,因此您可以像這樣傳播更改。 您只需每次都使用obj.var 當然,字符串(連同整數、元組、一些其他內置類型和其他幾種類型)是不可變的,即您無法更改任何內容以供他人查看,因為您根本無法更改它。

However, the mutability of objects opens another possibility: You could , if you bothered to pull it through, write a wrapper class that contains an arbitrary object, allows changing that object though a set() method and delegates everything important to that object. 不過,您可能遲早會遇到令人討厭的小麻煩。 例如,我無法想象這會與貫穿所有成員的元編程或任何認為它必須搞砸的東西很好地配合。 它也是令人難以置信的hacky(即不可靠)。 可能有一個更簡單的解決方案。

(On a side note, PyPy has a become function in one of its non-default object spaces that really and truly replaces one object with another, visible to everyone with a reference to that object. It doesn't work with any other implementations though而且我認為令人難以置信的潛在和誤用混淆以及我們大多數人很少需要的事實使得它在實際代碼中幾乎不可接受。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM