IT박스

파이썬의 주요 방법 이해하기

itboxs 2020. 6. 17. 19:22
반응형

파이썬의 주요 방법 이해하기


이 질문에는 이미 답변이 있습니다.

저는 Python을 처음 사용하지만 다른 OOP 언어에 대한 경험이 있습니다. 내 코스는 파이썬의 주요 방법을 설명하지 않습니다.

파이썬에서 주요 메소드가 어떻게 작동하는지 알려주세요. Java와 비교하려고하기 때문에 혼란 스럽습니다.

def main():
# display some lines

if __name__ == "__main__": main()

어떻게 주요 실행되고 왜 나는이 이상한 필요합니까 if실행할 main. 를 제거하면 코드가 출력되지 않고 종료됩니다 if.

최소한의 코드-

class AnimalActions:
    def quack(self): return self.strings['quack']
    def bark(self): return self.strings['bark']

class Duck(AnimalActions):
    strings = dict(
        quack = "Quaaaaak!",
        bark = "The duck cannot bark.",
    )


class Dog(AnimalActions):
    strings = dict(
        quack = "The dog cannot quack.",
        bark = "Arf!",
    )

def in_the_doghouse(dog):
    print(dog.bark())

def in_the_forest(duck):
    print(duck.quack())

def main():
    donald = Duck()
    fido = Dog()

    print("- In the forest:")
    for o in ( donald, fido ):
        in_the_forest(o)

    print("- In the doghouse:")
    for o in ( donald, fido ):
        in_the_doghouse(o)

if __name__ == "__main__": main()

"main"에 대한 파이썬 접근 방식은 언어 (*)에 거의 고유합니다.

의미는 약간 미묘합니다. __name__가 가져 오는 것 같은 식별자는 모든 모듈의 이름에 바인드됩니다. 그러나 파일이 실행될 때 (리터럴 문자열 :)로 __name__설정됩니다 ."__main__"__main__

이것은 거의 항상 기능을 정의하는 코드 부분과 실행되어야하는 코드 부분을 분리하는 데 사용됩니다. 따라서 파이썬 코드에는 종종 다음과 같은 줄이 포함됩니다.

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

이 규칙을 사용하면 파일에 다른 프로그램에서 사용할 클래스와 함수를 정의 할 수 있으며 파일을 독립형 스크립트로 호출 할 때만 평가하는 코드도 포함 할 수 있습니다.

It's important to understand that all of the code above the if __name__ line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print statement before the if __name__ line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__" to isolate a block of code which calls a suite of unit tests that apply to this module.

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

Summary: if __name__ == '__main__': has two primary use cases:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.

It's fairly common to def main(*args) and have if __name__ == '__main__': simply call main(*sys.argv[1:]) if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module() and calling test_module() in your if __name__ == '__main__:' suite.

  • (Ruby also implements a similar feature if __file__ == $0).

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

meth1
main code

More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.


Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.


If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

참고URL : https://stackoverflow.com/questions/22492162/understanding-the-main-method-of-python

반응형