What are the possible reasons behind the malfunctioning of my attributes after I replaced my method with a new one

My Computer Science lessons have been focused on Object Orientated Programming, but the code provided as an example seems to be malfunctioning.

class bankAccount(): 

    '''This is a bank account class'''

    def __init__(self, account_name = "Bank Account", balance = 1500):
        self.__account_name = account_name 
        self.__balance = balance 

    def deposit(self, value): 
        self.__balance = self.__balance + value 
        print("You now have: ", self.__balance) 

    def withdraw(self, value): 
        self.__balance = self.__balance - value 
        print("You now have: ", self.__balance) 

class currentAccount(bankAccount): 

    '''This is a current account class''' 

    def __init__(self, account_name = "Current Account", balance = 1500): 
        self.__account_name = account_name 
        self.__balance = balance

        super().__init__() 

    def withdraw(self, value): 

        if value > 1000: 
            print("You will have to phone the bank manager") 

        else: 
            self.__balance = self.__balance - value 
            print("You now have: ", self.__balance) 

class savingsAccount(bankAccount): 

    '''This is a current account class''' 

    def __init__(self, account_name = "Savings Account", balance = 1500): 
        self.__account_name = account_name 
        self.__balance = balance 

        super().__init__() 

    def deposit(self, value): 
        self.__balance = self.__balance + (value *1.03) 
        print("You now have: ", self.__balance) 

currentObject = currentAccount() 

savingsObject = savingsAccount() 

while True: 
    print("1. Current Account") 
    print("2. Savings Account")

    menu_option = int(input()) 

    if menu_option == 1: 
        print("1. Deposit funds") 
        print("2. Withdraw funds") 

        submenu_option = int(input()) 

        if submenu_option == 1: 
            value = int(input("How much would you like to deposit? ")) 
            currentObject.deposit(value) 

        elif submenu_option == 2: 
            value = int(input("How much would you like to withdraw? ")) 
            currentObject.withdraw(value) 
        else: 
            print("Wrong menu choice!") 

    elif menu_option == 2: 
        print("1. Deposit funds") 
        print("2. Withdraw funds")

        submenu_option = int(input()) 

        if submenu_option == 1: 
            value = int(input("How much would you like to deposit? ")) 
            savingsObject.deposit(value) 

        elif submenu_option == 2: 
            value = int(input("How much would you like to withdraw? ")) 
            savingsObject.withdraw(value) 

        else: 
            print("Wrong menu choice!") 

    else: 
        print("Wrong menu choice!") 

input() 

Upon examination, it appears that distinct data is saved for each withdrawal and deposit transaction. This leads to discrepancies in the balance when performing these operations. If you were to deposit $100 into a savings account and then withdraw $100, instead of calculating (1500 + 100) = 1600 followed by (1600 - 100), the program defaults to using 1500 as the initial balance, resulting in different balances for deposits and withdrawals.

I am seeking assistance with this issue since I am new to OOP and unable to discern the cause behind this behavior. Any guidance provided would be highly valued.

Answer №1

The source of the issue arises from utilizing self.__balance. The presence of double underscores in the attribute names leads to a scenario where Name Mangling is activated: Understanding single and double underscore usage in object names

To rectify this problem, it is recommended to change all class attribute names by prefixing them with a single underscore:

class bankAccount(): 

    '''An implementation of a bank account class'''

   def __init__(self, account_name = "Bank Account", balance = 1500):
        self._account_name = account_name 
        self._balance = balance 

    def deposit(self, value): 
       self._balance = self._balance + value 
        print("Your new balance: ", self._balance) 

    def withdraw(self, value): 
        self._balance = self._balance - value 
        print("Your new balance: ", self._balance) 
    
class currentAccount(bankAccount): 

    '''A subclass representing a current account''' 

    def __init__(self, account_name = "Current Account", balance = 1500): 
        self._account_name = account_name 
        self._balance = balance

        super().__init__() 

    def withdraw(self, value): 

        if value > 1000: 
            print("Please contact the bank manager") 

        else: 
            self._balance = self._balance - value 
            print("Your new balance: ", self._balance) 

class savingsAccount(bankAccount): 

     '''A subclass representing a savings account''' 

    def __init__(self, account_name = "Savings Account", balance = 1500): 
        self._account_name = account_name 
        self._balance = balance 

        super().__init__() 

    def deposit(self, value): 
        self._balance = self._balance + (value *1.03) 
        print("Your new balance: ", self._balance) 

currentObject = currentAccount() 

savingsObject = savingsAccount() 

while True: 
    print("1. Current Account") 
    print("2. Savings Account")

    menu_option = int(input()) 

    if menu_option == 1: 
        print("1. Deposit funds") 
        print("2. Withdraw funds")

        submenu_option = int(input()) 

        if submenu_option == 1: 
            value = int(input("Enter deposit amount: ")) 
            currentObject.deposit(value) 

        elif submenu_option == 2: 
            value = int(input("Enter withdrawal amount: ")) 
            currentObject.withdraw(value) 
        else: 
            print("Invalid choice!") 

    elif menu_option == 2: 
        print("1. Deposit funds") 
        print("2. Withdraw funds")

        submenu_option = int(input()) 

        if submenu_option == 1: 
            value = int(input("Enter deposit amount: ")) 
            savingsObject.deposit(value) 

        elif submenu_option == 2: 
            value = int(input("Enter withdrawal amount: ")) 
            savingsObject.withdraw(value) 

        else: 
            print("Invalid choice!") 

    else: 
        print("Invalid choice!") 

input()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tallying Columns in Python for VLOOKUPS

Just starting out with Python and trying to apply it to a minor annoyance I encounter while using VLOOKUPS in Excel. Our databases are huge, with over 15,000 lines and columns spanning up to GG. I need an easy way to determine the column number for the loo ...

The evaluation was not able to finish due to an error encountered when using the send_keys function in

In my Python 2.7 environment, I am using Selenium version 3.4.3: search_field= self.driver.find_element(By.ID ,'Searchbox') time.sleep(10) search_field.send_keys('test' + Keys.RETURN) This code works perfectly in Chrome and Firefox, ...

Prevent simultaneous access to the same element in the queue

Currently, I am in the process of reviewing and refactoring a queue system that is designed to be used concurrently by up to 20 individuals. However, at the moment, multiple users are able to access the first element simultaneously (We tested this by click ...

What is the best way to display a sequence of boxplots on the x-axis using dates as labels?

I'm trying to include boxplots on a graph with an x-axis that represents a range of dates. Here is the code I have so far: fig = make_subplots(rows = 2, columns = 1) fig.add_trace(go.Scatter(x = df['Date'], y = df['Measure']), row ...

The audio recording quality of pjsua2 looped recordings is absolutely dreadful

I have successfully implemented a basic caller and listener script with the following functionality: The Listener waits for a call The Caller initiates the call The Caller plays a wav file (transmitted from pj.AudioMediaPlayer instance to playback_media) ...

Using Python Selenium can lead to obtaining diverse outcomes when utilizing the driver.find_elements method

Just starting out with selenium and I've encountered a problem that has me stumped: When using a direct link in driver.get(), I can find and count elements without any issues by using: element.driver.find_elements_by_xpath(); print(len(element)) ...

Unable to close Asynchronous Web.py Web Server

Referring to this example, I am curious why it's not possible to terminate this program using Ctrl+C: #!/usr/bin/env python import web import threading class MyWebserver(threading.Thread): def run (self): urls = ('/', 'MyWebse ...

A Python program for testing with Unittest, including input and output file capabilities

I have created a program that consists of one function. This function takes a file as input and writes the result to an output file. I now need to test whether the result matches the expected output. Below is the code for the program: import os def userna ...

Create a hierarchical dictionary structure by nesting dictionaries containing child elements from an array

Let's say I have fetched an array of dicts from a web API. Each dict contains keys like name, description, 'parent', and children. The children key consists of an array of dicts. Here is a hypothetical example for better understanding: [ ...

Dividing PyQt5 logic from UI results in dysfunctional functions

After following the guidelines to separate my program's functionality from the Ui class (created by PyQt5 Designer) as mentioned here and here, I encountered an issue. When running logic.py, the Ui displays correctly but the program functions do not w ...

Establishing live video streaming with OpenCV via sockets in Python 3

I am currently working on a project to develop a simple application that can live stream video using Python 3 and OpenCV over a socket. I have limited experience with both OpenCV and socket programming, so any detailed answers would be greatly appreciated. ...

How can I assign values to columns based on a condition in a dataframe in Python?

My dataset consists of columns such as maxlevel, level1id, level2id, level3id. I am looking to create a new column called newcol_value depending on the values in the maxlevel column. If maxlevel equals 1, then I want to assign the value of level1id to ne ...

The sequence in which sess.run([op1, op2...]) is executed within TensorFlow

Curious about the sequence of operations in sess.run(ops_list, ...). For instance, in a standard classification scenario: _, loss = sess.run([train_op, loss_op]), if train_op is executed first, the loss will be calculated after the current backpropagatio ...

Utilizing Selenium with Python to Extract Link Text Value from Subchild Element in Various Scenarios

I'm currently working with the following code snippet: <div class="_97KWR"> <div class="_12x3s"> <div class="_1PF0y"> <div class="_1xNd0 CTwrR _3ASIK"> <a class="_3bf_k _1WIu4" href="/en/gilgamesh/hola-dola/g ...

Retrieve data from a file in CSV format and separate it into two distinct lists: one for strings and the other for integers

I have the following CSV data: Jim 57 83 55 78 John 98 91 80 Michael 61 88 80 60 Harry 92 58 50 57 James 51 97 52 53 I need to format it without using the CSV module. For empty values, I want to display "Non ...

Transfer data from JSON column in DataFrame to individual rows in the DataFrame

Encountering a dilemma that needs resolution. Among my assets is a JSON file featuring nested dictionaries in one of its columns. To bring this JSON data into a DataFrame, I utilize the following code: df2=pd.read_json(filename) The resulting DataFrame co ...

The issue with the value of the textarea in Selenium automated tests using

I have a webpage with Javascript where I've implemented a textarea using the following code: var textarea = $("<textarea>"); textarea.change(() => { console.log(textarea.val()); }); When I update the value in the textarea and then chang ...

Restricting outcomes using Jinja in Python

Is there a way to limit the displayed results in Jinja based on specific criteria? For instance, if I had a CSV file with the following information: Agent ID DOB 152 31/07/1993 175 05/12/1997 And my template setup looks like this: filename = ...

Decisions need to be capable of being iterated through

I'm encountering an issue related to Django and Python. The specific error message I am seeing is .from_hour: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Could someone provide clarifica ...

Django has been reported to unexpectedly automatically assigning a `None` value to a field during the validation

Encountering a peculiar problem with django. After running is_valid() on the formset, one value in each subform turns into None. To investigate, I added debug lines printing the cleaned_data dict at two different points: once at the end of cleaned_qty(), a ...