Error using global variables

I am confused why my usage of the amount variable in the deposit function results in an error saying that the amount variable is not defined.

class Category:
    global ammount, ledger
    amount = 0
    ledger = []

    def __init__(self, category):
        self.category = category

    def deposit(self, addamount, description=""):
        amount += addamount

Why would you make these global anyways?

I am trying to kind of replicate a java feature in which I can go like this:

public class Test{
private int hi;
public static void add() {
hi += 1;

Is this possible in python?

Python doesn’t have a concept of public and private members of an object. By polite agreement, data that is intended to be private is prefaced with an underscore, but all object attributes are publicly accessible.

I was referring to the aspect that a variable cane declared inside a class and be used by all functions inside the class

is this possible in python?

The same variable for every instance of the class? You can do that, but it tends to lead to very counterintuitive results and is considered an antipattern.


Yeah the error happens because “global” isn’t doing what you think it does.
The keyword actually tells Python to “look” for the global variable, not creating it. Meaning without using global amount in your deposit(), Python creates amount as local varibale there. Which then throws an error because Python can’t += a variable that’s not yet initialized.

1 Like