我有一个班级,我期待这个:
print(rithesh.amount) = 150.
我该怎么做?
这是我的代码:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
def add_amount(self, amount):
self.amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1@gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
答案 0 :(得分:5)
您可以将__init__
方法中的金额变量声明为0
。然后对add_amount
方法进行一些小改动。
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1@gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
<强>输出强>
150
答案 1 :(得分:1)
在python中拥有属性的实际方法是使用@property decorator
例如,在您的班级中:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
@property
def add_amount(self):
return self.add_amount
@add_amount.setter
def add_amount(self, amount):
self.add_amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1@gmail.com")
rithesh.add_amount = 150
print(rithesh.add_amount)
答案 2 :(得分:0)
知道怎么做。
我必须在初始化期间声明值self.amount = 0.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Ritehsh", "8892398598", "ritheshb1@gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
因此输出为print(rithesh.amount)= 150
答案 3 :(得分:-2)
当您拨打add_amount
时,您没有将值添加到self.amount
,而只是设置它。
只需更改add_amount
的定义:
self.amount = amount
为:
self.amount += amount
并添加到__init__
方法:
self.amount = 0