I want to use the d
value from can_add
method for add
method, but get error 'MoneyBox' object has no attribute 'd'
. How to use d
value for add
method?
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
self.v = v
if self.capacity > self.v:
self.d = True
return d
else:
self.d = False
return self.d
def add(self, v):
self.can_add(v)
if self.d == True:
self.v = v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)
CodePudding user response:
d isn't a variable of the class but only in can_add
method hence you can't access it in add
method.
more so, you don't need it anyway, just return true/false.
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
if self.capacity > v:
return True
else:
return False
def add(self, v):
if self.can_add(v) == True:
v = v
f = self.capacity - v
return f
a = MoneyBox(10)
a.add(5)
CodePudding user response:
You are trying to return a class variable when you want to return a local variable.
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
self.v = v
if self.capacity > self.v:
d = True
return d
else:
d = False
return d
def add(self, v):
d = self.can_add(v)
if d == True:
self.v = v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)
If you want the value to be saved in a class variable you can do it like this
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
self.d = False
def can_add(self, v):
self.v = v
if self.capacity > self.v:
self.d = True
else:
self.d = False
def add(self, v):
self.can_add(v)
if self.d == True:
self.v = v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)
CodePudding user response:
You don't need the can_add
method to return anything since when you call it in add
, self.d
attribute is already updated. So just change can_add
to the following and everything will work as expected:
def can_add(self, v):
self.v = v
if self.capacity > self.v:
self.d = True
else:
self.d = False
That being said, I strongly suggest initializing all class instance variables in __init__
so that your definitions are all in one place and it's more readable. So like:
def __init__(self, capacity = 0):
self.capacity = capacity
self.v = None
self.d = None