不使用继承,我们可以在一个类的两个实例之间共享一个变量吗? 问题在于该变量需要3.5GB。使用继承不是一个好选择,因为我可能会也可能不会加载此变量。
答案 0 :(得分:2)
您可以为此使用类变量。请看下面一个家庭共享一个帐户的简单示例。
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
如果您要使用
10
以外的其他值来初始化类变量,例如0
,则可以如下修改上述代码。
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