[英]How to change instance variable when another related instance variable is changed in a class?
[英]When I use one base class for two different classes, and change a variable within one class instance, the variable in the other class is also changed?
下面的源代碼將在最后一行引發異常。 如果它們是兩個不同的對象,為什么會引發異常?
class BaseClass(object):
accounts = dict()
def AddAccount(self, account_id, account_var):
if account_id in self.accounts.keys():
raise Exception('Account already exists')
self.accounts.update({account_id: account_var})
class Class1(BaseClass):
pass
class Class2(BaseClass):
pass
ACCOUNT_ID = '123'
c1 = Class1()
c2 = Class2()
c1.AddAccount(ACCOUNT_ID, 'abc')
c2.AddAccount(ACCOUNT_ID, 'abc')
我試過在每個 class 中調用構造函數,但這並不能解決問題。 我在每個 class 中都這樣做了:
def __init__(self):
super().__init__()
看起來BaseClass
始終是 static object。 當我換一個 object 時,它會換另一個。
您已經在BaseClass
的主體中定義了 class 變量。
即使您使用self.accounts
引用它,它也不是實例變量。
例如,如果你想要一個實例變量,你應該在__init__()
中使用self.accounts = {}
初始化它
您已將accounts
定義為 class 的變量,而不是實例變量。 相反,您應該在基礎 class 的__init__
方法中定義accounts
,以便為您創建的每個 class 實例使用不同的引用對其進行實例化。
class BaseClass(object):
def __init__(self):
self.accounts = dict()
def AddAccount(self, account_id, account_var):
if account_id in self.accounts.keys():
raise Exception('Account already exists')
self.accounts.update({account_id: account_var})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.