should function be defined before it is used in python?

前端 未结 3 1762
不思量自难忘°
不思量自难忘° 2021-01-24 18:45

should the functions be defined before it is used? but why the following code works:

def main():
    dog()

def dog():
    print(\"This is a dog.\")

if __name__         


        
3条回答
  •  有刺的猬
    2021-01-24 19:00

    The name dog is looked up as a global. References to globals do not need to be referring to anything defined until they are actually used. The function main() doesn't use dog until it is called.

    If dog was not defined, calling main() would result in a NameError exception:

    >>> def main():
    ...     return dog()
    ... 
    >>> main()
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 2, in main
    NameError: global name 'dog' is not defined
    >>> def dog():
    ...     return 'Woof!'
    ... 
    >>> main()
    'Woof!'
    

    Python doesn't really care what dog is. I can make it a class too, or something that is not callable even:

    >>> class dog:
    ...     pass
    ... 
    >>> main()
    <__main__.dog instance at 0x10f7d3488>
    >>> dog = 'Some string'
    >>> main()
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 2, in main
    TypeError: 'str' object is not callable
    

    Because in the last example, dog is now bound to a string, the main function fails when trying to call it.

提交回复
热议问题