having issues affecting the value of an initialized class through methods in python. it keeps overriding the value

38 views Asked by At
class SmarJug:
    """"smart jug class  needs to be initially set contents to the value of 100"""
    def __init__(self, contents=100):
        self._contents = contents


    def pour(self):
        if self._contents == 0:
            print(f'Sorry this jug is empty!')
        else:
            print(f'Pouring...')
            self._contents = int(self._contents) - 25
            print(self._contents)
        

issue is that when i run test1.pour() logic happens but the initial value is set to 100 again

tes1 = SmarJug()
tes1.pour()
1

There are 1 answers

0
OneCricketeer On

Nothing you've shown resets the value. Sounds like you are expecting the variable to be stored across multiple executions of the code. This is not true. Every time you define tes1 = SmarJug(), the initial contents=100. Therefore each run "resets" the value...

If you want to persist the object state across runs, then you'll need to save/load the contents into a file, for example

import json
with open('jug.json') as f:
    contents = json.load(f).get("contents")
if contents is None:
    tes1 = SmarJug()
else:
    tes1 = SmarJug(int(contents))

tes1.pour()

jug = {"contents" : tes1._contents} 
with open('jug.json') as f:
    contents = json.dump(jug, f)