[英]Store an instance of a class within another class method
在Python 3中,有沒有一種方法可以存儲一個類的實例以供另一個類的方法多次使用? 我有這樣的課程...
class ObjectOne:
def __init__(self):
#initializes multiple different instances of ObjectTwo
self.ObjectTwoInstance = ObjectTwo(...)
def print_output(self):
#prints some output from initialized objects
class ObjectTwo:
def __init__(self):
#some initialization
def change_object(self):
"""Changes some state of an ObjectTwo Instance"""
#creates a new instance of ObjectOne, and overrides
#the default ObjectOne instance's initialization of
#ObjectTwo. (I want to be able to refer back to this
#new instance of ObjectOne, and change that instead
#of changing another default ObjectOne object)
我的問題來自ObjectTwo中的change_object方法。 可能有更好的方法來執行此操作,但是從本質上講,我希望能夠保存ObjectOne的更新后的新實例,以便下次我調用change_object時可以引用該新實例,並更改該實例而不是基礎實例。初始化的ObjectOne實例。
在當前情況下,每當我嘗試調用change_object時,它都會在新的ObjectOne實例中更改ObjectTwo的初始化,但是只是更新ObjectOne的默認初始化,因為change_object不知道我上次調用它時更新的ObjectOne實例。 (我正努力避免混淆,但這是我能夠解釋的最好方法)
如果有更簡單的方法可以執行此操作,還是需要重組代碼? 無論哪種情況,我都不確定該如何處理。
(編輯:更改了ObjectOne的__init__
以使我的問題更清楚)
我不確定您要做什么,但似乎肯定有更好的方法可以做到...
假設我理解正確的你-你想創建修改后的單獨實例ObjectOne
每一個實例ObjectTwo
然后用change_object
上的相應實例ObjectOne
,我建議建立的修改實例ObjectOne
內__init__
:
class ObjectTwo:
def __init__(self):
self.ObjectOneInstance = ObjectOne()
# override the default ObjectOne's initialization of ObjectTwo,
# however you did it originally in change_object
# some other initialization
def change_object(self):
# change some state of the ObjectTwo instance
# perform operation on self.ObjectOneInstance
我還建議考慮定義一個新類,例如ObjectOneModified
,該類繼承ObjectOne
。 此類將在ObjectTwo
而不是ObjectOne
,並且可以修改其__init__
而不影響ObjectOne
的原始(默認)定義。
我最終通過將解決我的問題ObjectOne
到ObjectTwo
通過ObjectTwo
的__init__
,就像這樣:
class ObjectTwo:
def __init__(self, object_one):
self.object_one_instance = object_one
def change_object(self):
"""Changes some state of an ObjectTwo Instance"""
#modifies self.object_one_instance, and updates
#the instance
這類似於ViAik的建議,但不涉及創建新類或初始化全新實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.