Python: How Do I Fix My Code So That The Append Will Add The Argument To The List?
Solution 1:
A few issues you need to deal with. First assigning f=True
outside the class won't change the value inside, so if you instantiated the class it would just throw an UnboundLocalError
complaining that f isn't initialized. You can try this yourself by instantiating the class with
fc = firstclass()
Without instantiation, you have no hope of it giving you the value you want. It is printing zero because of the function secondclass, which has a print statement that is not contained within a method, so it prints the value sum(prices)
which the class is declared. That value is from the original declared value of prices which is []
. At least that is the way you have shown it in your question. I'm not sure whether you meant to indent the print statement, which would mean it is part of secondclass. However, if you didn't indent you would get the same result as you haven't instantiated firstclass.
To correct this, see below. This code will output 70 as you intended.
prices = []
classfirstclass():
def__init__(self):
my_function()
defmy_function():
prices.append(70)
classsecondclass():
def__init__(self):
passprint('before instantiation', sum(prices))
fc = firstclass()
print('after instantiation', sum(prices))
fc is now an object of type firstclass
and the __init__
method has called my_function
to append the value 70 to prices
.
Solution 2:
There are two reasons this is happening.
- You never called
firstclass
to actually initialize the constructor. - You are trying to assign
False
to the variablef
which does not belong to the scope of the class. If you still assign it, it's considered local. And at the moment the interpreter detects that you assigned it, the while loop does not have any local reference off
since you did not define it under the constructor. See this answer for more details.
Here is the completed code:
prices = []
classfirstclass():
f = Truedef__init__(self):
while self.f:
my_function()
self.f = Falsedefmy_function():
prices.append(70)
classsecondclass():
def__init__(self):
pass
firstclass()
print(sum(prices))
Post a Comment for "Python: How Do I Fix My Code So That The Append Will Add The Argument To The List?"