Why Is this possible? - Budget App Project

Question: Why Is it possible to referencing something that is not defined yet?

Hi everyone, I’ve been searching and thinking for hours why Is this possible, but I don’t understand it, I would be glad to read your explanations.

def withdraw(self, amount, description=""):
      A withdraw method that is similar to the deposit method, but the amount passed in should be stored in the ledger as a negative number. If there are not enough funds, nothing should be added to the ledger. This method should return True if the withdrawal took place, and False otherwise

        self.ledger.append({"amount": -amount, "description": description})
        return True
      return False

In this block of code check_funds is not defined yet and It’s possible to referencing it. Why?

Thank you.

The existence of self.check_funds is only checked at the point that you call it. That means that you are free to define it later, or never, as long as you don’t try to use the withdraw function before you’ve defined it.

You can try it out in IDLE as below, and you will get no errors until the final line:

class foo:
    def bar (self, amount):
        if (self.check_funds(amount)):

f = foo()
f.bar(5) ### this line causes an error
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
  File "<pyshell#4>", line 3, in bar
    if (self.check_funds(amount)):
AttributeError: 'foo' object has no attribute 'check_funds'


Thank you so much : D.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.