Python中类的两个实例之间共享的变量



如果不使用继承,我们可以在一个类的两个实例之间共享一个变量吗?问题是这个变量需要3.5GB。使用继承不是一个好的选择,因为我可能加载也可能不加载这个变量。

您可以为此使用类变量。请看下面一个简单的例子,一个家庭共享一个帐户。

https://www.tutorialspoint.com/python/python_classes_objects.htm

class FamilyAccount(object):
total_amount = 0 # class variable
def __init__(self, fullname, age):
self.fullname = fullname # instance variable
self.age = age           # instance variable
def credit(self, amount):
FamilyAccount.total_amount += amount
def debit(self, amount):
FamilyAccount.total_amount -= amount
def details(self):
print("Fullname: ", self.fullname)
print("Age     : ", self.age)
print("Amount  : ", self.total_amount)
print() # new line
# Create account for Rishikesh Agrawani
account1 = FamilyAccount("Rishikesh Agrawani", 26)
# Rishikesh Agrawani credits 1000
account1.credit(1000)
# Print account information of Rishikesh Agrawani
account1.details() # 1000

# Create account for Shay Banon
account2 = FamilyAccount("Shay Banon", 30)
# Shay Banon debits 500
account2.debit(500)
# Print account information of Shay Banon
account2.details() # 500
# Print account information of Rishikesh Agrawani (again)
account1.details() # 500
# Fullname:  Rishikesh Agrawani
# Age     :  26
# Amount  :  1000
# Fullname:  Shay Banon
# Age     :  30
# Amount  :  500
# Fullname:  Rishikesh Agrawani
# Age     :  26
# Amount  :  500

如果您想用0以外的其他值(如10(初始化类变量,可以按如下方式修改上面的代码。

class FamilyAccount(object):
total_amount = 0 # class variable
def __init__(self, fullname, age, amount = 0, set_amount = False):
if set_amount: 
# If you want to reset amount for all members
# total_amount will be re-intialized (visible to all instances)
FamilyAccount.total_amount = amount
self.fullname = fullname # instance variable
self.age = age           # instance variable
def credit(self, amount):
FamilyAccount.total_amount += amount
def debit(self, amount):
FamilyAccount.total_amount -= amount
def details(self):
print("Fullname: ", self.fullname)
print("Age     : ", self.age)
print("Amount  : ", self.total_amount)
print() # new line
# Create account for Rishikesh Agrawani
account1 = FamilyAccount("Rishikesh Agrawani", 26, 10, set_amount = True)
# Rishikesh Agrawani credits 1000
account1.credit(1000)
# Print account information of Rishikesh Agrawani
account1.details() # 1010

# Create account for Shay Banon
account2 = FamilyAccount("Shay Banon", 30)
# Shay Banon debits 500
account2.debit(500)
# Print account information of Shay Banon
account2.details() # 510
# Print account information of Rishikesh Agrawani (again)
account1.details() # 510
# Fullname:  Rishikesh Agrawani
# Age     :  26
# Amount  :  1010
# Fullname:  Shay Banon
# Age     :  30
# Amount  :  510
# Fullname:  Rishikesh Agrawani
# Age     :  26
# Amount  :  510

最新更新