0

I tried to inherit "Person" class to "Student" class:

class Student(Person):
  pass

class Person:
  pass

But I got this error:

NameError: name 'Person' is not defined

So, I changed the order of "Student" and "Person" classes:

class Person:
  pass

class Student(Person):
  pass

Finally, the error was solved.

Does Python basically execute code from the top to the bottom?

If yes, are there any special cases which Python executes code from the bottom to the top or which Python doesn't care about the order of code?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • 1
    Yes, Python executes top to bottom. There are no special cases where it does otherwise, as far as I know. – wim Mar 18 '22 at 07:26
  • There are languages which distinguish between compile-time and runtime code, where it's possible to, for example, call functions before they've been declared, because function declarations are processed at compile-time, but calls at runtime. However, even in those languages, you usually need to define logical relationships in a logical order. I.e. even if class declarations were processed at compile-time, the compiler will still need to know about parent classes before you can try to inherit them. – deceze Mar 18 '22 at 07:29
  • If you do `print(1)` followed by `print(2 + 3)`, actually the `2 + 3` gets computed first. – Kelly Bundy Mar 18 '22 at 07:40
  • @KellyBundy Wat? – deceze Mar 18 '22 at 07:43
  • @deceze It gets computed during compilation and stored as the constant `5`, which is later loaded and used. See the [disassembly](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRCEls5iLC0joAbGGuro6V0FRZl6JhqEmlGGkoK1grMkFlNH8/x8A). – Kelly Bundy Mar 18 '22 at 07:47
  • 1
    @Kelly That's a compiler optimisation, not sure I'd put this in the same category. It doesn't change anything about the program behaviour like OP's example would. – deceze Mar 18 '22 at 08:05
  • @deceze It's half joke, half the-only-thing-I-can-think-of-even-remotely-like-what-they're-asking-for. They did ask for "*any* special cases". – Kelly Bundy Mar 18 '22 at 08:12

0 Answers0