Skip to content Skip to sidebar Skip to footer

How Are We Able To Call Functions Before They Are Defined In Python?

In Python functional programming this code is valid and runs as expected: def increment_5(num): number = 5 number += num disp_result(num) def disp_result(num): pri

Solution 1:

You can't call a function before it's defined. disp_result isn't called until increment_5 is called.

For example, this will fail:

defincrement_5(num):
    number = 5
    number += num
    disp_result(num)

increment_5()  # -> NameError: name 'disp_result' is not defineddefdisp_result(num):
    print(f"5 was increased by {num}")

While this will succeed:

defincrement_5(num):
    number = 5
    number += num
    disp_result(num)

defdisp_result(num):
    print(f"5 was increased by {num}")

increment_5(4)  # -> 5 was increased by 4

Solution 2:

As opposed to classes, function bodies are not executed without explicitly calling the function. Follow along:

>>>classA:...print('hello')...
hello
>>>deff():...print('hello')...
# <nothing happens>

Since Python does not execute the function body until you call that function, you can populate the scopes where that function might look for specific names after defining it.

Solution 3:

The reason why code such as this works:

classFoo():defmethod1(self):
        self.method2()

    defmethod2(self):
        print("hello")

f = Foo()
f.method1()

is that the variable self.method2 inside Foo.method1 is only evaluated (and the function to which it points only gets called) at the time that the code inside Foo.method1 is actually executed, not while it is being defined.

Before class Foo can be instantiated, the class definition must first have completed (i.e. the class object must have been created and it must have been populated with all of its methods). Therefore at the time when the instance f exists and f.method1() (or equivalently, Foo.method1(f)) is called, the instance object (passed to the method via its self argument) already has a property method2 inherited from the class, which has by that time been fully populated.

It therefore does not matter in which order methods are declared within a class.

This is a completely different situation from trying to call a function before it has been defined.

Post a Comment for "How Are We Able To Call Functions Before They Are Defined In Python?"