# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2017, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , 2017. # msgid "" msgstr "" "Project-Id-Version: Python 3.6\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-10-11 20:40+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: Dong-gweon Oh \n" "Language-Team: Korean (https://python.flowdas.com)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.17.0\n" #: ../../tutorial/classes.rst:5 msgid "Classes" msgstr "클래스" #: ../../tutorial/classes.rst:7 msgid "" "Classes provide a means of bundling data and functionality together. " "Creating a new class creates a new *type* of object, allowing new " "*instances* of that type to be made. Each class instance can have " "attributes attached to it for maintaining its state. Class instances can" " also have methods (defined by its class) for modifying its state." msgstr "" "클래스는 데이터와 기능을 함께 묶는 방법을 제공합니다. 새 클래스를 만드는 것은 객체의 새 *형* 을 만들어서, 그 형의 새 " "*인스턴스* 를 만들 수 있도록 합니다. 각 클래스 인스턴스는 상태를 유지하기 위해 그 자신에게 첨부된 어트리뷰트를 가질 수 " "있습니다. 클래스 인스턴스는 상태를 바꾸기 위한 (클래스에 의해 정의된) 메서드도 가질 수 있습니다." #: ../../tutorial/classes.rst:13 msgid "" "Compared with other programming languages, Python's class mechanism adds " "classes with a minimum of new syntax and semantics. It is a mixture of " "the class mechanisms found in C++ and Modula-3. Python classes provide " "all the standard features of Object Oriented Programming: the class " "inheritance mechanism allows multiple base classes, a derived class can " "override any methods of its base class or classes, and a method can call " "the method of a base class with the same name. Objects can contain " "arbitrary amounts and kinds of data. As is true for modules, classes " "partake of the dynamic nature of Python: they are created at runtime, and" " can be modified further after creation." msgstr "" "다른 프로그래밍 언어들과 비교할 때, 파이썬의 클래스 메커니즘은 최소한의 새로운 문법과 개념을 써서 클래스를 추가합니다. C++ 과" " 모듈라-3 에서 발견되는 클래스 메커니즘을 혼합합니다. 파이썬 클래스는 객체 지향형 프로그래밍의 모든 표준 기능들을 제공합니다: " "클래스 상속 메커니즘은 다중 베이스 클래스를 허락하고, 자식 클래스는 베이스 클래스나 클래스들의 어떤 메서드도 재정의할 수 있으며," " 메서드는 같은 이름의 베이스 클래스의 메서드를 호출할 수 있습니다. 객체들은 임의의 종류의 데이터를 양적 제한 없이 가질 수 " "있습니다. 모듈과 마찬가지로, 클래스는 파이썬의 동적인 본성을 함께 나눕니다: 실행 시간에 만들어지고, 만들어진 후에도 더 수정될 " "수 있습니다." #: ../../tutorial/classes.rst:23 msgid "" "In C++ terminology, normally class members (including the data members) " "are *public* (except see below :ref:`tut-private`), and all member " "functions are *virtual*. As in Modula-3, there are no shorthands for " "referencing the object's members from its methods: the method function is" " declared with an explicit first argument representing the object, which " "is provided implicitly by the call. As in Smalltalk, classes themselves " "are objects. This provides semantics for importing and renaming. Unlike" " C++ and Modula-3, built-in types can be used as base classes for " "extension by the user. Also, like in C++, most built-in operators with " "special syntax (arithmetic operators, subscripting etc.) can be redefined" " for class instances." msgstr "" "C++ 용어로, 보통 클래스 멤버들은 (데이터 멤버를 포함해서) *public* (예외는 아래 :ref:`tut-private` 를" " 보세요) 하고, 모든 맴버 함수들은 *virtual* 입니다. 모듈라-3처럼, 객체의 매소드에서 그 객체의 멤버를 참조하는 줄임 " "표현은 없습니다: 메서드 함수는 그 객체를 표현하는 명시적인 첫 번째 인자를 선언하는데, 함수 호출 때 묵시적으로 제공됩니다. " "스몰토크처럼, 클래스 자신도 객체입니다. 이것이 임포팅과 이름 변경을 위한 개념을 제공합니다. C++ 나 모듈라-3 와는 달리, " "내장형도 사용자가 확장하기 위해 베이스 클래스로 사용할 수 있습니다. 또한, C++ 처럼, 특별한 문법을 갖는 대부분의 내장 " "연산자들은 (산술 연산자, 서브스크립팅, 등등) 클래스 인스턴스에 대해 새로 정의될 수 있습니다." #: ../../tutorial/classes.rst:34 msgid "" "(Lacking universally accepted terminology to talk about classes, I will " "make occasional use of Smalltalk and C++ terms. I would use Modula-3 " "terms, since its object-oriented semantics are closer to those of Python " "than C++, but I expect that few readers have heard of it.)" msgstr "" "(클래스에 대해 보편적으로 받아들여지는 용어들이 없는 상태에서, 이따금 스몰토크나 C++ 용어들을 사용할 것입니다. C++ 보다 " "객체 지향적 개념들이 파이썬의 것과 더 가까우므로 모듈라-3 용어를 사용할 수도 있지만, 들어본 독자들이 별로 없을 것으로 " "예상합니다.)" #: ../../tutorial/classes.rst:43 msgid "A Word About Names and Objects" msgstr "이름과 객체에 관한 한마디" #: ../../tutorial/classes.rst:45 msgid "" "Objects have individuality, and multiple names (in multiple scopes) can " "be bound to the same object. This is known as aliasing in other " "languages. This is usually not appreciated on a first glance at Python, " "and can be safely ignored when dealing with immutable basic types " "(numbers, strings, tuples). However, aliasing has a possibly surprising " "effect on the semantics of Python code involving mutable objects such as " "lists, dictionaries, and most other types. This is usually used to the " "benefit of the program, since aliases behave like pointers in some " "respects. For example, passing an object is cheap since only a pointer " "is passed by the implementation; and if a function modifies an object " "passed as an argument, the caller will see the change --- this eliminates" " the need for two different argument passing mechanisms as in Pascal." msgstr "" "객체는 개체성(individuality)을 갖고, 여러 개의 이름이 (여러 개의 스코프에서) 같은 객체에 연결될 수 있습니다. " "이것은 다른 언어들에서는 에일리어싱(aliasing) 이라고 알려져 있습니다. 보통 파이썬을 처음 볼 때 이 점을 높이 평가하지는 " "않고, 불변 기본형들 (숫자, 문자열, 튜플)을 다루는 동안은 안전하게 무시할 수 있습니다. 하지만, 에일리어싱는 리스트, " "딕셔너리나 그 밖의 다른 가변 객체들을 수반하는 파이썬 코드의 의미에 극적인 효과를 줄 수 있습니다. 이것은 보통 프로그램에 혜택이" " 되는데, 에일리어스는 어떤 면에서 포인터처럼 동작하기 때문입니다. 예를 들어, 구현이 포인터만 전달하기 때문에, 객체를 전달하는 " "비용이 적게 듭니다; 그리고 함수가 인자로 전달된 객체를 수정하면, 호출자는 그 변경을 보게 됩니다 --- 이것은 파스칼에서 " "사용되는 두 가지 서로 다른 인자 전달 메커니즘의 필요를 제거합니다." #: ../../tutorial/classes.rst:61 msgid "Python Scopes and Namespaces" msgstr "파이썬 스코프와 이름 공간" #: ../../tutorial/classes.rst:63 msgid "" "Before introducing classes, I first have to tell you something about " "Python's scope rules. Class definitions play some neat tricks with " "namespaces, and you need to know how scopes and namespaces work to fully " "understand what's going on. Incidentally, knowledge about this subject is" " useful for any advanced Python programmer." msgstr "" "클래스를 소개하기 전에, 파이썬의 스코프 규칙에 대해 몇 가지 말할 것이 있습니다. 클래스 정의는 이름 공간으로 깔끔한 요령을 " "부리고, 여러분은 무엇이 일어나는지 완전히 이해하기 위해 스코프와 이름 공간이 어떻게 동작하는지 알 필요가 있습니다. 덧붙여 " "말하자면, 이 주제에 대한 지식은 모든 고급 파이썬 프로그래머에게 쓸모가 있습니다." #: ../../tutorial/classes.rst:69 msgid "Let's begin with some definitions." msgstr "몇 가지 정의로 시작합시다." #: ../../tutorial/classes.rst:71 msgid "" "A *namespace* is a mapping from names to objects. Most namespaces are " "currently implemented as Python dictionaries, but that's normally not " "noticeable in any way (except for performance), and it may change in the " "future. Examples of namespaces are: the set of built-in names " "(containing functions such as :func:`abs`, and built-in exception names);" " the global names in a module; and the local names in a function " "invocation. In a sense the set of attributes of an object also form a " "namespace. The important thing to know about namespaces is that there is" " absolutely no relation between names in different namespaces; for " "instance, two different modules may both define a function ``maximize`` " "without confusion --- users of the modules must prefix it with the module" " name." msgstr "" "*이름 공간* 은 이름에서 객체로 가는 매핑입니다. 대부분의 이름 공간은 현재 파이썬 딕셔너리로 구현되어 있지만, 보통 다른 " "식으로는 알아차릴 수 없고 (성능은 예외입니다), 앞으로는 바뀔 수 있습니다. 이름 공간의 예는: 내장 이름들의 집합 " "(:func:`abs` 와 같은 함수들과 내장 예외 이름들을 포함합니다); 모듈의 전역 이름들; 함수 호출에서의 지역 이름들. 어떤" " 의미에서 객체의 어트리뷰트 집합도 이름 공간을 형성합니다. 이름 공간에 대해 알아야 할 중요한 것은 서로 다른 이름 공간들의 이름" " 간에는 아무런 관계가 없다는 것입니다; 예를 들어, 두 개의 서로 다른 모듈들은 모두 혼동 없이 함수 ``maximize`` 를 " "정의할 수 있습니다 --- 모듈의 사용자들은 모듈 이름을 앞에 붙여야 합니다." #: ../../tutorial/classes.rst:82 msgid "" "By the way, I use the word *attribute* for any name following a dot --- " "for example, in the expression ``z.real``, ``real`` is an attribute of " "the object ``z``. Strictly speaking, references to names in modules are " "attribute references: in the expression ``modname.funcname``, ``modname``" " is a module object and ``funcname`` is an attribute of it. In this case" " there happens to be a straightforward mapping between the module's " "attributes and the global names defined in the module: they share the " "same namespace! [#]_" msgstr "" "그런데, 저는 *어트리뷰트* 라는 단어를 점 뒤에 오는 모든 이름에 사용합니다 --- 예를 들어, 표현식 ``z.real`` 에서," " ``real`` 는 객체 ``z`` 의 어트리뷰트입니다. 엄밀하게 말해서, 모듈에 있는 이름들에 대한 참조는 어트리뷰트 " "참조입니다: 표현식 ``modname.funcname`` 에서, ``modname`` 은 모듈 객체고 ``funcname`` 는 " "그것의 어트리뷰트입니다. 이 경우에는 우연히도 모듈의 어트리뷰트와 모듈에서 정의된 전역 이름 간에 직접적인 매핑이 생깁니다: 같은 " "이름 공간을 공유합니다! [#]_" #: ../../tutorial/classes.rst:90 msgid "" "Attributes may be read-only or writable. In the latter case, assignment " "to attributes is possible. Module attributes are writable: you can write" " ``modname.the_answer = 42``. Writable attributes may also be deleted " "with the :keyword:`del` statement. For example, ``del " "modname.the_answer`` will remove the attribute :attr:`!the_answer` from " "the object named by ``modname``." msgstr "" "어트리뷰트는 읽기 전용 이거나 쓰기 가능할 수 있습니다. 후자의 경우, 어트리뷰트에 대한 대입이 가능합니다. 모듈 어트리뷰트는 쓰기" " 가능합니다: ``modname.the_answer = 42`` 라고 쓸 수 있습니다. 쓰기 가능한 어트리뷰트는 " ":keyword:`del` 문으로 삭제할 수도 있습니다. 예를 들어, ``del modname.the_answer`` 는 " "``modname`` 라는 이름의 객체에서 어트리뷰트 :attr:`!the_answer` 를 제거합니다." #: ../../tutorial/classes.rst:96 msgid "" "Namespaces are created at different moments and have different lifetimes." " The namespace containing the built-in names is created when the Python " "interpreter starts up, and is never deleted. The global namespace for a " "module is created when the module definition is read in; normally, module" " namespaces also last until the interpreter quits. The statements " "executed by the top-level invocation of the interpreter, either read from" " a script file or interactively, are considered part of a module called " ":mod:`__main__`, so they have their own global namespace. (The built-in " "names actually also live in a module; this is called :mod:`builtins`.)" msgstr "" "이름 공간들은 서로 다른 순간에 만들어지고 서로 다른 수명을 갖습니다. 내장 이름들을 담는 이름 공간은 파이썬 인터프리터가 시작할 " "때 만들어지고 영원히 지워지지 않습니다. 모듈의 전역 이름 공간은 모듈 정의를 읽는 동안 만들어집니다; 보통, 모듈 이름 공간은 " "인터프리터가 끝날 때까지 남습니다. 인터프리터의 최상위 호출 때문에 실행되는, 스크립트 파일이나 대화형으로 읽히는, 문장들은 " ":mod:`__main__` 이라고 불리는 모듈 일부로 여겨져서 그 들 자신의 이름 공간을 갖습니다. (내장 이름들 또한 모듈에 " "속하는데; 이것을 :mod:`builtins` 라 부릅니다.)" #: ../../tutorial/classes.rst:106 msgid "" "The local namespace for a function is created when the function is " "called, and deleted when the function returns or raises an exception that" " is not handled within the function. (Actually, forgetting would be a " "better way to describe what actually happens.) Of course, recursive " "invocations each have their own local namespace." msgstr "" "함수의 지역 이름 공간은 함수가 호출될 때 만들어지고, 함수가 복귀하거나 함수 내에서 처리되지 않는 예외를 일으킬 때 삭제됩니다. " "(사실, 잊어버린다는 것이 실제로 일어나는 일에 대한 더 좋은 설명입니다.) 물론, 재귀적 호출은 각각 자기 자신만의 지역 이름 " "공간을 갖습니다." #: ../../tutorial/classes.rst:112 msgid "" "A *scope* is a textual region of a Python program where a namespace is " "directly accessible. \"Directly accessible\" here means that an " "unqualified reference to a name attempts to find the name in the " "namespace." msgstr "" "*스코프* 는 이름 공간을 직접 액세스할 수 있는 파이썬 프로그램의 텍스트 적인 영역입니다. 여기에서 \"직접 액세스 가능한\" " "이란 이름에 대한 정규화되지 않은 참조가 그 이름 공간에서 이름을 찾으려고 시도한다는 의미입니다." #: ../../tutorial/classes.rst:116 msgid "" "Although scopes are determined statically, they are used dynamically. At " "any time during execution, there are 3 or 4 nested scopes whose " "namespaces are directly accessible:" msgstr "" "스코프가 정적으로 결정됨에도 불구하고, 동적으로 사용됩니다. 실행 중 어느 시점에서건, 이름 공간을 직접 액세스 가능한, 세 개나 " "네 개의 중첩된 스코프가 있습니다:" #: ../../tutorial/classes.rst:120 msgid "the innermost scope, which is searched first, contains the local names" msgstr "가장 먼저 검색되는, 가장 내부의 스코프는 지역 이름들을 포함합니다" #: ../../tutorial/classes.rst:121 msgid "" "the scopes of any enclosing functions, which are searched starting with " "the nearest enclosing scope, contain non-local, but also non-global names" msgstr "" "둘러싸고 있는 함수들의 스코프는, 가장 가까이서 둘러싸는 스코프로부터 검색이 시작됩니다, 비 지역(non-local) 이지만 비 " "전역(non-global) 이름들을 포함합니다" #: ../../tutorial/classes.rst:123 msgid "the next-to-last scope contains the current module's global names" msgstr "마지막 직전의 스코프는 현재 모듈의 전역 이름들을 포함합니다" #: ../../tutorial/classes.rst:124 msgid "" "the outermost scope (searched last) is the namespace containing built-in " "names" msgstr "(가장 나중에 검색되는) 가장 외부의 스코프는 내장 이름들을 포함하고 있는 이름 공간입니다." #: ../../tutorial/classes.rst:126 msgid "" "If a name is declared global, then all references and assignments go " "directly to the next-to-last scope containing the module's global names." " To rebind variables found outside of the innermost scope, the " ":keyword:`nonlocal` statement can be used; if not declared nonlocal, " "those variables are read-only (an attempt to write to such a variable " "will simply create a *new* local variable in the innermost scope, leaving" " the identically named outer variable unchanged)." msgstr "" "이름을 global로 선언하면, 모든 참조와 대입은 모듈의 전역 이름들을 포함하는 마지막 바로 전 스코프로 바로 갑니다. 가장 " "내부의 스코프 바깥에서 발견되는 변수들을 재연결하려면, :keyword:`nonlocal` 키워드를 사용할 수 있습니다; " "nonlocal 로 선언되지 않으면, 그 변수들은 읽기 전용입니다 (그런 변수에 쓰려고 하면 단순히 가장 내부의 스코프에 *새* " "지역 변수를 만들게 되어, 같은 이름의 바깥 변수를 바꾸지 않고 남겨둡니다)." #: ../../tutorial/classes.rst:133 msgid "" "Usually, the local scope references the local names of the (textually) " "current function. Outside functions, the local scope references the same" " namespace as the global scope: the module's namespace. Class definitions" " place yet another namespace in the local scope." msgstr "" "보통, 지역 스코프는 현재 함수의 지역 이름들을 (텍스트 적으로) 참조합니다. 함수 바깥에서, 지역 스코프는 전역 스코프와 같은 " "이름 공간을 참조합니다: 모듈의 이름 공간. 클래스 정의들은 지역 스코프에 또 하나의 이름 공간을 배치합니다." #: ../../tutorial/classes.rst:138 msgid "" "It is important to realize that scopes are determined textually: the " "global scope of a function defined in a module is that module's " "namespace, no matter from where or by what alias the function is called." " On the other hand, the actual search for names is done dynamically, at " "run time --- however, the language definition is evolving towards static " "name resolution, at \"compile\" time, so don't rely on dynamic name " "resolution! (In fact, local variables are already determined " "statically.)" msgstr "" "스코프가 텍스트 적으로 결정된다는 것을 깨닫는 것은 중요합니다: 모듈에서 정의된 함수의 전역 스코프는, 어디에서 어떤 에일리어스를 " "통해 그 함수가 호출되는지에 관계없이, 그 모듈의 이름 공간입니다. 반면에, 이름을 실제로 검색하는 것은 실행시간에 동적으로 " "수행됩니다 --- 하지만, 언어 정의는 컴파일 시점의 정적인 이름 결정을 향해 진화하고 있어서, 동적인 이름 결정에 의존하지 말아야" " 합니다! (사실, 지역 변수들은 이미 정적으로 결정됩니다.)" #: ../../tutorial/classes.rst:146 msgid "" "A special quirk of Python is that -- if no :keyword:`global` or " ":keyword:`nonlocal` statement is in effect -- assignments to names always" " go into the innermost scope. Assignments do not copy data --- they just " "bind names to objects. The same is true for deletions: the statement " "``del x`` removes the binding of ``x`` from the namespace referenced by " "the local scope. In fact, all operations that introduce new names use " "the local scope: in particular, :keyword:`import` statements and function" " definitions bind the module or function name in the local scope." msgstr "" "파이썬의 특별한 특징은 -- :keyword:`global`\\이나 :keyword:`nonlocal` 문이 없을 때 -- 이름에 " "대입하면 항상 가장 내부의 스코프로 간다는 것입니다. 대입은 데이터를 복사하지 않습니다 -- 이름을 단지 객체에 연결할 뿐입니다. " "삭제도 마찬가지입니다: 문장 ``del x`` 는 지역 스코프가 참조하는 이름 공간에서 ``x`` 의 연결을 제거합니다. 사실, 새" " 이름을 소개하는 모든 연산은 지역 스코프를 사용합니다: 특히, :keyword:`import` 문과 함수 정의는 모듈이나 함수 " "이름을 지역 스코프에 연결합니다." #: ../../tutorial/classes.rst:154 msgid "" "The :keyword:`global` statement can be used to indicate that particular " "variables live in the global scope and should be rebound there; the " ":keyword:`nonlocal` statement indicates that particular variables live in" " an enclosing scope and should be rebound there." msgstr "" ":keyword:`global` 문은 특정 변수가 전역 스코프에 있으며 그곳에 재연결되어야 함을 가리킬 때 사용될 수 있습니다; " ":keyword:`nonlocal` 문은 특정 변수가 둘러싸는 스코프에 있으며 그곳에 재연결되어야 함을 가리킵니다." #: ../../tutorial/classes.rst:162 msgid "Scopes and Namespaces Example" msgstr "스코프와 이름 공간 예" #: ../../tutorial/classes.rst:164 msgid "" "This is an example demonstrating how to reference the different scopes " "and namespaces, and how :keyword:`global` and :keyword:`nonlocal` affect " "variable binding::" msgstr "" "이것은 어떻게 서로 다른 스코프와 이름 공간을 참조하고, :keyword:`global` 과 :keyword:`nonlocal` 이" " 변수 연결에 어떤 영향을 주는지를 보여주는 예입니다::" #: ../../tutorial/classes.rst:168 msgid "" "def scope_test():\n" " def do_local():\n" " spam = \"local spam\"\n" "\n" " def do_nonlocal():\n" " nonlocal spam\n" " spam = \"nonlocal spam\"\n" "\n" " def do_global():\n" " global spam\n" " spam = \"global spam\"\n" "\n" " spam = \"test spam\"\n" " do_local()\n" " print(\"After local assignment:\", spam)\n" " do_nonlocal()\n" " print(\"After nonlocal assignment:\", spam)\n" " do_global()\n" " print(\"After global assignment:\", spam)\n" "\n" "scope_test()\n" "print(\"In global scope:\", spam)" msgstr "" "def scope_test():\n" " def do_local():\n" " spam = \"local spam\"\n" "\n" " def do_nonlocal():\n" " nonlocal spam\n" " spam = \"nonlocal spam\"\n" "\n" " def do_global():\n" " global spam\n" " spam = \"global spam\"\n" "\n" " spam = \"test spam\"\n" " do_local()\n" " print(\"After local assignment:\", spam)\n" " do_nonlocal()\n" " print(\"After nonlocal assignment:\", spam)\n" " do_global()\n" " print(\"After global assignment:\", spam)\n" "\n" "scope_test()\n" "print(\"In global scope:\", spam)" #: ../../tutorial/classes.rst:191 msgid "The output of the example code is:" msgstr "예제 코드의 출력은 이렇게 됩니다:" #: ../../tutorial/classes.rst:193 msgid "" "After local assignment: test spam\n" "After nonlocal assignment: nonlocal spam\n" "After global assignment: nonlocal spam\n" "In global scope: global spam" msgstr "" "After local assignment: test spam\n" "After nonlocal assignment: nonlocal spam\n" "After global assignment: nonlocal spam\n" "In global scope: global spam" #: ../../tutorial/classes.rst:200 msgid "" "Note how the *local* assignment (which is default) didn't change " "*scope_test*\\'s binding of *spam*. The :keyword:`nonlocal` assignment " "changed *scope_test*\\'s binding of *spam*, and the :keyword:`global` " "assignment changed the module-level binding." msgstr "" "어떻게 *지역* 대입이 (이것이 기본입니다) *scope_test* 의 *spam* 연결을 바꾸지 않는지에 유의하세요. " ":keyword:`nonlocal` 대입은 *scope_test* 의 *spam* 연결을 바꾸고 :keyword:`global` " "대입은 모듈 수준의 연결을 바꿉니다." #: ../../tutorial/classes.rst:205 msgid "" "You can also see that there was no previous binding for *spam* before the" " :keyword:`global` assignment." msgstr ":keyword:`global` 대입 전에는 *spam* 의 연결이 없다는 것도 볼 수 있습니다." #: ../../tutorial/classes.rst:212 msgid "A First Look at Classes" msgstr "클래스와의 첫 만남" #: ../../tutorial/classes.rst:214 msgid "" "Classes introduce a little bit of new syntax, three new object types, and" " some new semantics." msgstr "클래스는 약간의 새 문법과 세 개의 객체형과 몇 가지 새 개념들을 도입합니다." #: ../../tutorial/classes.rst:221 msgid "Class Definition Syntax" msgstr "클래스 정의 문법" #: ../../tutorial/classes.rst:223 msgid "The simplest form of class definition looks like this::" msgstr "클래스 정의의 가장 간단한 형태는 이렇게 생겼습니다::" #: ../../tutorial/classes.rst:225 msgid "" "class ClassName:\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class ClassName:\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:232 msgid "" "Class definitions, like function definitions (:keyword:`def` statements) " "must be executed before they have any effect. (You could conceivably " "place a class definition in a branch of an :keyword:`if` statement, or " "inside a function.)" msgstr "" "함수 정의(:keyword:`def` 문)처럼, 클래스 정의는 어떤 효과가 생기기 위해서는 먼저 실행되어야 합니다. (상상컨대 " "클래스 정의를 :keyword:`if` 문의 분기나 함수 내부에 놓을 수 있습니다)" #: ../../tutorial/classes.rst:236 msgid "" "In practice, the statements inside a class definition will usually be " "function definitions, but other statements are allowed, and sometimes " "useful --- we'll come back to this later. The function definitions " "inside a class normally have a peculiar form of argument list, dictated " "by the calling conventions for methods --- again, this is explained " "later." msgstr "" "실재적으로, 클래스 정의 내부의 문장들은 보통 함수 정의들이지만, 다른 문장들도 허락되고 때로 쓸모가 있습니다 --- 나중에 이 " "주제로 돌아올 것입니다. 클래스 내부의 함수 정의는 보통, 메서드 호출 규약의 영향을 받은, 특별한 형태의 인자 목록을 갖습니다. " "--- 다시, 이것은 뒤에서 설명됩니다." #: ../../tutorial/classes.rst:242 msgid "" "When a class definition is entered, a new namespace is created, and used " "as the local scope --- thus, all assignments to local variables go into " "this new namespace. In particular, function definitions bind the name of" " the new function here." msgstr "" "클래스 정의에 진입할 때, 새 이름 공간이 만들어지고 지역 스코프로 사용됩니다 --- 그래서, 모든 지역 변수들로의 대입은 이 새 " "이름 공간으로 갑니다. 특히, 함수 정의는 새 함수의 이름을 이곳에 연결합니다." #: ../../tutorial/classes.rst:247 msgid "" "When a class definition is left normally (via the end), a *class object* " "is created. This is basically a wrapper around the contents of the " "namespace created by the class definition; we'll learn more about class " "objects in the next section. The original local scope (the one in effect" " just before the class definition was entered) is reinstated, and the " "class object is bound here to the class name given in the class " "definition header (:class:`!ClassName` in the example)." msgstr "" "클래스 정의가 (끝을 통해) 정상적으로 끝날 때, *클래스 객체* 가 만들어집니다. 이것은 기본적으로 클래스 정의 때문에 만들어진 " "이름 공간의 내용물들을 감싸는 싸개입니다; 다음 섹션에서 클래스 객체에 대해 더 배우게 됩니다. 원래의 지역 스코프가 (클래스 " "정의에 들어가기 직전에 유효하던 것) 다시 사용되고, 클래스 객체는 클래스 정의 헤더에서 주어진 클래스 이름 (예에서 " ":class:`!ClassName`) 으로 여기에 연결됩니다." #: ../../tutorial/classes.rst:259 msgid "Class Objects" msgstr "클래스 객체" #: ../../tutorial/classes.rst:261 msgid "" "Class objects support two kinds of operations: attribute references and " "instantiation." msgstr "클래스 객체는 두 종류의 연산을 지원합니다: 어트리뷰트 참조와 인스턴스 만들기." #: ../../tutorial/classes.rst:264 msgid "" "*Attribute references* use the standard syntax used for all attribute " "references in Python: ``obj.name``. Valid attribute names are all the " "names that were in the class's namespace when the class object was " "created. So, if the class definition looked like this::" msgstr "" "*어트리뷰트 참조* 는 파이썬의 모든 어트리뷰트 참조에 사용되는 표준 문법을 사용합니다: ``obj.name``. 올바른 어트리뷰트" " 이름은 클래스 객체가 만들어질 때 클래스의 이름 공간에 있던 모든 이름입니다. 그래서, 클래스 정의가 이렇게 될 때::" #: ../../tutorial/classes.rst:269 msgid "" "class MyClass:\n" " \"\"\"A simple example class\"\"\"\n" " i = 12345\n" "\n" " def f(self):\n" " return 'hello world'" msgstr "" "class MyClass:\n" " \"\"\"A simple example class\"\"\"\n" " i = 12345\n" "\n" " def f(self):\n" " return 'hello world'" #: ../../tutorial/classes.rst:276 msgid "" "then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, " "returning an integer and a function object, respectively. Class " "attributes can also be assigned to, so you can change the value of " "``MyClass.i`` by assignment. :attr:`~type.__doc__` is also a valid " "attribute, returning the docstring belonging to the class: ``\"A simple " "example class\"``." msgstr "" "``MyClass.i`` 와 ``MyClass.f`` 는 올바른 어트리뷰트 참조고, 각기 정수와 함수 객체를 돌려줍니다. 클래스 " "어트리뷰트는 대입할 수도 있어서, 대입을 통해 ``MyClass.i`` 의 값을 변경할 수 있습니다. " ":attr:`~type.__doc__` 도 역시 올바른 어트리뷰트고, 클래스에 속하는 독스트링을 돌려줍니다: ``\"A simple" " example class\"``." #: ../../tutorial/classes.rst:282 msgid "" "Class *instantiation* uses function notation. Just pretend that the " "class object is a parameterless function that returns a new instance of " "the class. For example (assuming the above class)::" msgstr "" "클래스 *인스턴스 만들기* 는 함수 표기법을 사용합니다. 클래스 객체가 클래스의 새 인스턴스를 돌려주는 매개변수 없는 함수인 " "체합니다. 예를 들어 (위의 클래스를 가정하면)::" #: ../../tutorial/classes.rst:286 ../../tutorial/classes.rst:303 msgid "x = MyClass()" msgstr "x = MyClass()" #: ../../tutorial/classes.rst:288 msgid "" "creates a new *instance* of the class and assigns this object to the " "local variable ``x``." msgstr "는 클래스의 새 *인스턴스* 를 만들고 이 객체를 지역 변수 ``x`` 에 대입합니다." #: ../../tutorial/classes.rst:291 msgid "" "The instantiation operation (\"calling\" a class object) creates an empty" " object. Many classes like to create objects with instances customized to" " a specific initial state. Therefore a class may define a special method " "named :meth:`~object.__init__`, like this::" msgstr "" "인스턴스 만들기 연산 (클래스 객체 \"호출하기\") 은 빈 객체를 만듭니다. 많은 클래스는 특정한 초기 상태로 커스터마이즈된 " "인스턴스로 객체를 만드는 것을 좋아합니다. 그래서 클래스는 이런 식으로 :meth:`~object.__init__` 라는 이름의 " "특수 메서드 정의할 수 있습니다::" #: ../../tutorial/classes.rst:296 msgid "" "def __init__(self):\n" " self.data = []" msgstr "" "def __init__(self):\n" " self.data = []" #: ../../tutorial/classes.rst:299 msgid "" "When a class defines an :meth:`~object.__init__` method, class " "instantiation automatically invokes :meth:`!__init__` for the newly " "created class instance. So in this example, a new, initialized instance " "can be obtained by::" msgstr "" "클래스가 :meth:`~object.__init__` 메서드를 정의할 때, 클래스 인스턴스 만들기는 새로 만들어진 클래스 인스턴스에" " 대해 자동으로 :meth:`!__init__` 를 호출합니다. 그래서 이 예에서, 새 초기화된 인스턴스를 이렇게 얻을 수 " "있습니다::" #: ../../tutorial/classes.rst:305 msgid "" "Of course, the :meth:`~object.__init__` method may have arguments for " "greater flexibility. In that case, arguments given to the class " "instantiation operator are passed on to :meth:`!__init__`. For example, " "::" msgstr "" "물론, :meth:`~object.__init__` 메서드는 더 높은 유연성을 위해 인자들을 가질 수 있습니다. 그 경우, 클래스 " "인스턴스 만들기 연산자로 주어진 인자들은 :meth:`!__init__` 로 전달됩니다. 예를 들어, ::" #: ../../tutorial/classes.rst:309 msgid "" ">>> class Complex:\n" "... def __init__(self, realpart, imagpart):\n" "... self.r = realpart\n" "... self.i = imagpart\n" "...\n" ">>> x = Complex(3.0, -4.5)\n" ">>> x.r, x.i\n" "(3.0, -4.5)" msgstr "" ">>> class Complex:\n" "... def __init__(self, realpart, imagpart):\n" "... self.r = realpart\n" "... self.i = imagpart\n" "...\n" ">>> x = Complex(3.0, -4.5)\n" ">>> x.r, x.i\n" "(3.0, -4.5)" #: ../../tutorial/classes.rst:322 msgid "Instance Objects" msgstr "인스턴스 객체" #: ../../tutorial/classes.rst:324 msgid "" "Now what can we do with instance objects? The only operations understood" " by instance objects are attribute references. There are two kinds of " "valid attribute names: data attributes and methods." msgstr "" "이제 인스턴스 객체로 무엇을 할 수 있을까? 인스턴스 객체가 이해하는 오직 한가지 연산은 어트리뷰트 참조입니다. 두 가지 종류의 " "올바른 어트리뷰트 이름이 있습니다: 데이터 어트리뷰트와 메서드." #: ../../tutorial/classes.rst:328 #, fuzzy msgid "" "*Data attributes* correspond to \"instance variables\" in Smalltalk, and " "to \"data members\" in C++. Data attributes need not be declared; like " "local variables, they spring into existence when they are first assigned " "to. For example, if ``x`` is the instance of :class:`!MyClass` created " "above, the following piece of code will print the value ``16``, without " "leaving a trace::" msgstr "" "*데이터 어트리뷰트* 는 스몰토크의 \"인스턴스 변수\" 에, C++ 의 \"데이터 멤버\" 에 해당합니다. 데이터 어트리뷰트는 " "선언될 필요 없습니다; 지역 변수처럼, 처음 대입될 때 태어납니다. 예를 들어, ``x`` 가 위에서 만들어진 " ":class:`!MyClass` 의 인스턴스면, 다음과 같은 코드 조각은 트레이스 없이 값 ``16`` 을 인쇄합니다::" #: ../../tutorial/classes.rst:334 msgid "" "x.counter = 1\n" "while x.counter < 10:\n" " x.counter = x.counter * 2\n" "print(x.counter)\n" "del x.counter" msgstr "" "x.counter = 1\n" "while x.counter < 10:\n" " x.counter = x.counter * 2\n" "print(x.counter)\n" "del x.counter" #: ../../tutorial/classes.rst:340 msgid "" "The other kind of instance attribute reference is a *method*. A method is" " a function that \"belongs to\" an object." msgstr "다른 인스턴스 어트리뷰트 참조는 *메서드* 입니다. 메서드는 객체에 \"속하는\" 함수입니다." #: ../../tutorial/classes.rst:345 msgid "" "Valid method names of an instance object depend on its class. By " "definition, all attributes of a class that are function objects define " "corresponding methods of its instances. So in our example, ``x.f`` is a " "valid method reference, since ``MyClass.f`` is a function, but ``x.i`` is" " not, since ``MyClass.i`` is not. But ``x.f`` is not the same thing as " "``MyClass.f`` --- it is a *method object*, not a function object." msgstr "" "인스턴스 객체의 올바른 메서드 이름은 그것의 클래스에 달려있습니다. 정의상, 함수 객체인 클래스의 모든 어트리뷰트들은 상응하는 " "인스턴스의 메서드들을 정의합니다. 그래서 우리의 예제에서, ``x.f`` 는 올바른 메서드 참조인데, ``MyClass.f`` 가 " "함수이기 때문입니다. 하지만 ``x.i`` 는 그렇지 않은데, ``MyClass.i`` 가 함수가 아니기 때문입니다. 그러나, " "``x.f`` 는 ``MyClass.f`` 와 같은 것이 아닙니다 --- 이것은 함수 객체가 아니라 *메서드 객체* 입니다." #: ../../tutorial/classes.rst:356 msgid "Method Objects" msgstr "메서드 객체" #: ../../tutorial/classes.rst:358 msgid "Usually, a method is called right after it is bound::" msgstr "보통, 메서드는 연결되자마자 호출됩니다::" #: ../../tutorial/classes.rst:360 msgid "x.f()" msgstr "x.f()" #: ../../tutorial/classes.rst:362 #, fuzzy msgid "" "If ``x = MyClass()``, as above, this will return the string ``'hello " "world'``. However, it is not necessary to call a method right away: " "``x.f`` is a method object, and can be stored away and called at a later " "time. For example::" msgstr "" ":class:`!MyClass` 예에서, 이것은 문자열 ``'hello world'`` 를 돌려줍니다. 하지만, 메서드를 즉시 " "호출할 필요는 없습니다: ``x.f`` 는 메서드 객체고, 저장된 후에 호출될 수 있습니다. 예를 들어::" #: ../../tutorial/classes.rst:366 msgid "" "xf = x.f\n" "while True:\n" " print(xf())" msgstr "" "xf = x.f\n" "while True:\n" " print(xf())" #: ../../tutorial/classes.rst:370 msgid "will continue to print ``hello world`` until the end of time." msgstr "는 영원히 계속 ``hello world`` 를 인쇄합니다." #: ../../tutorial/classes.rst:372 msgid "" "What exactly happens when a method is called? You may have noticed that " "``x.f()`` was called without an argument above, even though the function " "definition for :meth:`!f` specified an argument. What happened to the " "argument? Surely Python raises an exception when a function that requires" " an argument is called without any --- even if the argument isn't " "actually used..." msgstr "" "메서드가 호출될 때 정확히 어떤 일이 일어날까? :meth:`!f` 의 함수 정의가 인자를 지정했음에도 불구하고, 위에서 " "``x.f()`` 는 인자 없이 호출된 것을 알아챘을 것입니다. 인자는 어떻게 된 걸까? 확실히 파이썬은 인자를 필요로 하는 함수를" " 인자 없이 호출하면 예외를 일으킵니다 -- 인자가 실제로는 사용되지 않는다 해도..." #: ../../tutorial/classes.rst:378 msgid "" "Actually, you may have guessed the answer: the special thing about " "methods is that the instance object is passed as the first argument of " "the function. In our example, the call ``x.f()`` is exactly equivalent " "to ``MyClass.f(x)``. In general, calling a method with a list of *n* " "arguments is equivalent to calling the corresponding function with an " "argument list that is created by inserting the method's instance object " "before the first argument." msgstr "" "실제로, 여러분은 답을 짐작할 수 있습니다: 메서드의 특별함은 인스턴스 객체가 함수의 첫 번째 인자로 전달된다는 것입니다. 우리 " "예에서, 호출 ``x.f()``\\는 정확히 ``MyClass.f(x)`` 와 동등합니다. 일반적으로, *n* 개의 인자들의 " "목록으로 메서드를 호출하는 것은, 첫 번째 인자 앞에 메서드의 인스턴스 객체를 삽입해서 만든 인자 목록으로 상응하는 함수를 호출하는" " 것과 동등합니다." #: ../../tutorial/classes.rst:385 msgid "" "In general, methods work as follows. When a non-data attribute of an " "instance is referenced, the instance's class is searched. If the name " "denotes a valid class attribute that is a function object, references to " "both the instance object and the function object are packed into a method" " object. When the method object is called with an argument list, a new " "argument list is constructed from the instance object and the argument " "list, and the function object is called with this new argument list." msgstr "" "일반적으로, 메서드는 다음과 같이 작동합니다. 데이터 어트리뷰트가 아닌 인스턴스 어트리뷰트를 참조하면, 그것의 클래스가 검색됩니다." " 만약 그 이름이 함수 객체인 올바른 클래스 어트리뷰트면, 인스턴스 객체와 함수 객체에 대한 참조가 함께 메서드 객체로 포장됩니다." " 메서드 객체가 인자 목록으로 호출되면, 인스턴스 객체와 인자 목록으로부터 새 인자 목록이 구성된 후, 함수 객체를 이 새 인자 " "목록으로 호출합니다." #: ../../tutorial/classes.rst:398 msgid "Class and Instance Variables" msgstr "클래스와 인스턴스 변수" #: ../../tutorial/classes.rst:400 msgid "" "Generally speaking, instance variables are for data unique to each " "instance and class variables are for attributes and methods shared by all" " instances of the class::" msgstr "" "일반적으로 말해서, 인스턴스 변수는 인스턴스별 데이터를 위한 것이고 클래스 변수는 그 클래스의 모든 인스턴스에서 공유되는 " "어트리뷰트와 메서드를 위한 것입니다::" #: ../../tutorial/classes.rst:404 msgid "" "class Dog:\n" "\n" " kind = 'canine' # class variable shared by all instances\n" "\n" " def __init__(self, name):\n" " self.name = name # instance variable unique to each instance\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.kind # shared by all dogs\n" "'canine'\n" ">>> e.kind # shared by all dogs\n" "'canine'\n" ">>> d.name # unique to d\n" "'Fido'\n" ">>> e.name # unique to e\n" "'Buddy'" msgstr "" "class Dog:\n" "\n" " kind = 'canine' # 모든 인스턴스가 공유하는 클래스 변수\n" "\n" " def __init__(self, name):\n" " self.name = name # 각 인스턴스에 고유한 인스턴스 변수\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.kind # 모든 인스턴스가 공유하는 변수\n" "'canine'\n" ">>> e.kind # 모든 인스턴스가 공유하는 변수\n" "'canine'\n" ">>> d.name # d 만의 변수\n" "'Fido'\n" ">>> e.name # e 만의 변수\n" "'Buddy'" #: ../../tutorial/classes.rst:422 msgid "" "As discussed in :ref:`tut-object`, shared data can have possibly " "surprising effects with involving :term:`mutable` objects such as lists " "and dictionaries. For example, the *tricks* list in the following code " "should not be used as a class variable because just a single list would " "be shared by all *Dog* instances::" msgstr "" ":ref:`tut-object` 에서 논의했듯이, 리스트나 딕셔너리와 같은 :term:`가변 ` 객체가 참여할 때 " "공유 데이터는 예상치 못한 효과를 줄 가능성이 있습니다. 예를 들어, 다음 코드에서 *tricks* 리스트는 클래스 변수로 사용되지" " 않아야 하는데, 하나의 리스트가 모든 *Dog* 인스턴스들에 공유되기 때문입니다." #: ../../tutorial/classes.rst:428 msgid "" "class Dog:\n" "\n" " tricks = [] # mistaken use of a class variable\n" "\n" " def __init__(self, name):\n" " self.name = name\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks # unexpectedly shared by all dogs\n" "['roll over', 'play dead']" msgstr "" "class Dog:\n" "\n" " tricks = [] # 클래스 변수의 잘못된 사용\n" "\n" " def __init__(self, name):\n" " self.name = name\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks # 예기치 않게 모든 인스턴스가 공유합니다\n" "['roll over', 'play dead']" #: ../../tutorial/classes.rst:445 msgid "Correct design of the class should use an instance variable instead::" msgstr "대신, 클래스의 올바른 설계는 인스턴스 변수를 사용해야 합니다::" #: ../../tutorial/classes.rst:447 msgid "" "class Dog:\n" "\n" " def __init__(self, name):\n" " self.name = name\n" " self.tricks = [] # creates a new empty list for each dog\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks\n" "['roll over']\n" ">>> e.tricks\n" "['play dead']" msgstr "" "class Dog:\n" "\n" " def __init__(self, name):\n" " self.name = name\n" " self.tricks = [] # 각 인스턴스마다 새 빈 리스트를 만듭니다\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks\n" "['roll over']\n" ">>> e.tricks\n" "['play dead']" #: ../../tutorial/classes.rst:469 msgid "Random Remarks" msgstr "기타 주의사항들" #: ../../tutorial/classes.rst:473 msgid "" "If the same attribute name occurs in both an instance and in a class, " "then attribute lookup prioritizes the instance::" msgstr "인스턴스와 클래스 모두에서 같은 어트리뷰트 이름이 등장하면, 어트리뷰트 조회는 인스턴스를 우선합니다::" #: ../../tutorial/classes.rst:476 msgid "" ">>> class Warehouse:\n" "... purpose = 'storage'\n" "... region = 'west'\n" "...\n" ">>> w1 = Warehouse()\n" ">>> print(w1.purpose, w1.region)\n" "storage west\n" ">>> w2 = Warehouse()\n" ">>> w2.region = 'east'\n" ">>> print(w2.purpose, w2.region)\n" "storage east" msgstr "" ">>> class Warehouse:\n" "... purpose = 'storage'\n" "... region = 'west'\n" "...\n" ">>> w1 = Warehouse()\n" ">>> print(w1.purpose, w1.region)\n" "storage west\n" ">>> w2 = Warehouse()\n" ">>> w2.region = 'east'\n" ">>> print(w2.purpose, w2.region)\n" "storage east" #: ../../tutorial/classes.rst:488 msgid "" "Data attributes may be referenced by methods as well as by ordinary users" " (\"clients\") of an object. In other words, classes are not usable to " "implement pure abstract data types. In fact, nothing in Python makes it " "possible to enforce data hiding --- it is all based upon convention. (On" " the other hand, the Python implementation, written in C, can completely " "hide implementation details and control access to an object if necessary;" " this can be used by extensions to Python written in C.)" msgstr "" "데이터 어트리뷰트는 메서드 뿐만 아니라 객체의 일반적인 사용자 (\"클라이언트\")에 의해서 참조될 수도 있습니다. 달리 표현하면," " 클래스는 순수하게 추상적인 데이터형을 구현하는데 사용될 수 없습니다. 사실, 파이썬에서는 데이터 은닉을 강제할 방법이 없습니다 " "--- 모두 관례에 의존합니다. (반면에, C로 작성된 파이썬 구현은 필요하다면 구현 상세를 완전히 숨기고 객체에 대한 액세스를 " "제어할 수 있습니다; 이것은 C로 작성된 파이썬 확장에서 사용될 수 있습니다.)" #: ../../tutorial/classes.rst:496 msgid "" "Clients should use data attributes with care --- clients may mess up " "invariants maintained by the methods by stamping on their data " "attributes. Note that clients may add data attributes of their own to an" " instance object without affecting the validity of the methods, as long " "as name conflicts are avoided --- again, a naming convention can save a " "lot of headaches here." msgstr "" "클라이언트는 데이터 어트리뷰트를 조심스럽게 사용해야 합니다 --- 클라이언트는 데이터 어트리뷰트를 건드려서 메서드들에 의해 유지되는" " 불변성 들을 망가뜨릴 수 있습니다. 클라이언트는 이름 충돌을 피하는 한 메서드들의 유효성을 손상하지 않고도 그들 자신의 데이터 " "어트리뷰트를 인스턴스 객체에 추가할 수도 있음에 유의하세요 --- 다시 한번, 명명 규칙은 여러 골칫거리를 피할 수 있게 합니다." #: ../../tutorial/classes.rst:502 msgid "" "There is no shorthand for referencing data attributes (or other methods!)" " from within methods. I find that this actually increases the " "readability of methods: there is no chance of confusing local variables " "and instance variables when glancing through a method." msgstr "" "메서드 안에서 데이터 어트리뷰트들(또는 다른 메서드들!)을 참조하는 줄임 표현은 없습니다. 저는 이것이 실제로 메서드의 가독성을 " "높인다는 것을 알게 되었습니다: 메서드를 훑어볼 때 지역 변수와 인스턴스 변수를 혼동할 우려가 없습니다." #: ../../tutorial/classes.rst:507 msgid "" "Often, the first argument of a method is called ``self``. This is " "nothing more than a convention: the name ``self`` has absolutely no " "special meaning to Python. Note, however, that by not following the " "convention your code may be less readable to other Python programmers, " "and it is also conceivable that a *class browser* program might be " "written that relies upon such a convention." msgstr "" "종종, 메서드의 첫 번째 인자는 ``self`` 라고 불립니다. 이것은 관례일 뿐입니다: 이름 ``self`` 는 파이썬에서 아무런" " 특별한 의미를 갖지 않습니다. 하지만, 이 규칙을 따르지 않을 때 여러분의 코드가 다른 파이썬 프로그래머들이 읽기에 불편하고, " "*클래스 브라우저* 프로그램도 이런 규칙에 의존하도록 작성되었다고 상상할 수 있음에 유의하세요." #: ../../tutorial/classes.rst:513 msgid "" "Any function object that is a class attribute defines a method for " "instances of that class. It is not necessary that the function " "definition is textually enclosed in the class definition: assigning a " "function object to a local variable in the class is also ok. For " "example::" msgstr "" "클래스 어트리뷰트인 모든 함수는 그 클래스의 인스턴스들을 위한 메서드를 정의합니다. 함수 정의가 클래스 정의에 텍스트 적으로 " "둘러싸일 필요는 없습니다: 함수 객체를 클래스의 지역 변수로 대입하는 것 역시 가능합니다. 예를 들어::" #: ../../tutorial/classes.rst:518 msgid "" "# Function defined outside the class\n" "def f1(self, x, y):\n" " return min(x, x+y)\n" "\n" "class C:\n" " f = f1\n" "\n" " def g(self):\n" " return 'hello world'\n" "\n" " h = g" msgstr "" "# 클래스 외부에서 정의된 함수\n" "def f1(self, x, y):\n" " return min(x, x+y)\n" "\n" "class C:\n" " f = f1\n" "\n" " def g(self):\n" " return 'hello world'\n" "\n" " h = g" #: ../../tutorial/classes.rst:530 msgid "" "Now ``f``, ``g`` and ``h`` are all attributes of class :class:`!C` that " "refer to function objects, and consequently they are all methods of " "instances of :class:`!C` --- ``h`` being exactly equivalent to ``g``. " "Note that this practice usually only serves to confuse the reader of a " "program." msgstr "" "이제 ``f``, ``g``, ``h`` 는 모두 함수 객체를 가리키는 클래스 :class:`!C` 의 어트리뷰트고, 결과적으로 " "이것들은 모두 :class:`!C` 의 인스턴스들의 메서드입니다 --- ``h`` 는 정확히 ``g`` 와 동등합니다. 이런 방식은" " 프로그램의 독자들에게 혼란을 주기만 한다는 점에 주의하세요." #: ../../tutorial/classes.rst:535 msgid "" "Methods may call other methods by using method attributes of the ``self``" " argument::" msgstr "메서드는 ``self`` 인자의 메서드 어트리뷰트를 사용해서 다른 메서드를 호출할 수 있습니다::" #: ../../tutorial/classes.rst:538 msgid "" "class Bag:\n" " def __init__(self):\n" " self.data = []\n" "\n" " def add(self, x):\n" " self.data.append(x)\n" "\n" " def addtwice(self, x):\n" " self.add(x)\n" " self.add(x)" msgstr "" "class Bag:\n" " def __init__(self):\n" " self.data = []\n" "\n" " def add(self, x):\n" " self.data.append(x)\n" "\n" " def addtwice(self, x):\n" " self.add(x)\n" " self.add(x)" #: ../../tutorial/classes.rst:549 msgid "" "Methods may reference global names in the same way as ordinary functions." " The global scope associated with a method is the module containing its " "definition. (A class is never used as a global scope.) While one rarely" " encounters a good reason for using global data in a method, there are " "many legitimate uses of the global scope: for one thing, functions and " "modules imported into the global scope can be used by methods, as well as" " functions and classes defined in it. Usually, the class containing the " "method is itself defined in this global scope, and in the next section " "we'll find some good reasons why a method would want to reference its own" " class." msgstr "" "메서드는 일반 함수들과 마찬가지로 전역 이름을 참조할 수 있습니다. 메서드에 결합한 전역 스코프는 그것의 정의를 포함하는 " "모듈입니다. (클래스는 결코 전역 스코프로 사용되지 않습니다.) 메서드에서 전역 데이터를 사용할 좋은 이유를 거의 만나지 못하지만," " 전역 스코프를 정당하게 사용하는 여러 가지 경우가 있습니다: 한가지는, 전역 스코프에 정의된 함수와 메서드 뿐만 아니라, 그곳에 " "임포트된 함수와 모듈도 메서드가 사용할 수 있다는 것입니다. 보통, 메서드를 포함하는 클래스 자신은 이 전역 스코프에 정의되고, " "다음 섹션에서 메서드가 자신의 클래스를 참조하길 원하는 몇 가지 좋은 이유를 보게 될 것입니다." #: ../../tutorial/classes.rst:559 msgid "" "Each value is an object, and therefore has a *class* (also called its " "*type*). It is stored as ``object.__class__``." msgstr "" "각 값은 객체고, 그러므로 *클래스* (*형* 이라고도 불린다) 를 갖습니다. 이것은 ``object.__class__`` 에 " "저장되어 있습니다." #: ../../tutorial/classes.rst:566 msgid "Inheritance" msgstr "상속" #: ../../tutorial/classes.rst:568 msgid "" "Of course, a language feature would not be worthy of the name \"class\" " "without supporting inheritance. The syntax for a derived class " "definition looks like this::" msgstr "" "물론, 상속을 지원하지 않는다면 언어 기능은 \"클래스\"라는 이름을 붙일만한 가치가 없을 것입니다. 파생 클래스 정의의 문법은 " "이렇게 생겼습니다::" #: ../../tutorial/classes.rst:572 msgid "" "class DerivedClassName(BaseClassName):\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class DerivedClassName(BaseClassName):\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:579 msgid "" "The name :class:`!BaseClassName` must be defined in a namespace " "accessible from the scope containing the derived class definition. In " "place of a base class name, other arbitrary expressions are also allowed." " This can be useful, for example, when the base class is defined in " "another module::" msgstr "" "이름 :class:`!BaseClassName` 은 파생 클래스 정의를 포함하는 스코프에서 접근할 수 있는 이름 공간에 정의되어 " "있어야 합니다. 베이스 클래스 이름의 자리에 다른 임의의 표현식도 허락됩니다. 예를 들어, 베이스 클래스가 다른 모듈에 정의되어 " "있을 때 유용합니다::" #: ../../tutorial/classes.rst:585 msgid "class DerivedClassName(modname.BaseClassName):" msgstr "class DerivedClassName(modname.BaseClassName):" #: ../../tutorial/classes.rst:587 msgid "" "Execution of a derived class definition proceeds the same as for a base " "class. When the class object is constructed, the base class is " "remembered. This is used for resolving attribute references: if a " "requested attribute is not found in the class, the search proceeds to " "look in the base class. This rule is applied recursively if the base " "class itself is derived from some other class." msgstr "" "파생 클래스 정의의 실행은 베이스 클래스와 같은 방식으로 진행됩니다. 클래스 객체가 만들어질 때, 베이스 클래스가 기억됩니다. " "이것은 어트리뷰트 참조를 결정할 때 사용됩니다: 요청된 어트리뷰트가 클래스에서 발견되지 않으면 베이스 클래스로 검색을 확장합니다. " "베이스 클래스 또한 다른 클래스로부터 파생되었다면 이 규칙은 재귀적으로 적용됩니다." #: ../../tutorial/classes.rst:593 msgid "" "There's nothing special about instantiation of derived classes: " "``DerivedClassName()`` creates a new instance of the class. Method " "references are resolved as follows: the corresponding class attribute is " "searched, descending down the chain of base classes if necessary, and the" " method reference is valid if this yields a function object." msgstr "" "파생 클래스의 인스턴스 만들기에 특별한 것은 없습니다: ``DerivedClassName()`` 는 그 클래스의 새 인스턴스를 " "만듭니다. 메서드 참조는 다음과 같이 결정됩니다: 대응하는 클래스 어트리뷰트가 검색되는데, 필요하면 베이스 클래스의 연쇄를 타고 " "내려갑니다. 이것이 함수 객체를 준다면 메서드 참조는 올바릅니다." #: ../../tutorial/classes.rst:599 msgid "" "Derived classes may override methods of their base classes. Because " "methods have no special privileges when calling other methods of the same" " object, a method of a base class that calls another method defined in " "the same base class may end up calling a method of a derived class that " "overrides it. (For C++ programmers: all methods in Python are " "effectively ``virtual``.)" msgstr "" "파생 클래스는 베이스 클래스의 메서드들을 재정의할 수 있습니다. 메서드가 같은 객체의 다른 메서드를 호출할 때 특별한 권한 같은 " "것은 없으므로, 베이스 클래스에 정의된 다른 메서드를 호출하는 베이스 클래스의 메서드는 재정의된 파생 클래스의 메서드를 호출하게 " "됩니다. (C++ 프로그래머를 위한 표현으로: 파이썬의 모든 메서드는 실질적으로 ``virtual`` 입니다.)" #: ../../tutorial/classes.rst:605 msgid "" "An overriding method in a derived class may in fact want to extend rather" " than simply replace the base class method of the same name. There is a " "simple way to call the base class method directly: just call " "``BaseClassName.methodname(self, arguments)``. This is occasionally " "useful to clients as well. (Note that this only works if the base class " "is accessible as ``BaseClassName`` in the global scope.)" msgstr "" "파생 클래스에서 재정의된 메서드가, 같은 이름의 베이스 클래스 메서드를 단순히 갈아치우기보다 사실은 확장하고 싶을 수 있습니다. " "베이스 클래스의 메서드를 직접 호출하는 간단한 방법이 있습니다: 단지 ``BaseClassName.methodname(self, " "arguments)`` 를 호출하면 됩니다. 이것은 때로 클라이언트에게도 쓸모가 있습니다. (이것은 베이스 클래스가 전역 스코프에서" " ``BaseClassName`` 으로 액세스 될 수 있을 때만 동작함에 주의하세요.)" #: ../../tutorial/classes.rst:612 msgid "Python has two built-in functions that work with inheritance:" msgstr "파이썬에는 상속과 함께 사용할 수 있는 두 개의 내장 함수가 있습니다:" #: ../../tutorial/classes.rst:614 msgid "" "Use :func:`isinstance` to check an instance's type: ``isinstance(obj, " "int)`` will be ``True`` only if ``obj.__class__`` is :class:`int` or some" " class derived from :class:`int`." msgstr "" "인스턴스의 형을 검사하려면 :func:`isinstance` 를 사용합니다: ``isinstance(obj, int)`` 는 " "``obj.__class__`` 가 :class:`int` 거나 :class:`int` 에서 파생된 클래스인 경우만 ``True``" " 가 됩니다." #: ../../tutorial/classes.rst:618 msgid "" "Use :func:`issubclass` to check class inheritance: ``issubclass(bool, " "int)`` is ``True`` since :class:`bool` is a subclass of :class:`int`. " "However, ``issubclass(float, int)`` is ``False`` since :class:`float` is " "not a subclass of :class:`int`." msgstr "" "클래스 상속을 검사하려면 :func:`issubclass` 를 사용합니다: ``issubclass(bool, int)`` 는 " "``True`` 인데, :class:`bool` 이 :class:`int` 의 서브 클래스이기 때문입니다. 하지만, " "``issubclass(float, int)`` 는 ``False`` 인데, :class:`float` 는 :class:`int` " "의 서브 클래스가 아니기 때문입니다." #: ../../tutorial/classes.rst:628 msgid "Multiple Inheritance" msgstr "다중 상속" #: ../../tutorial/classes.rst:630 msgid "" "Python supports a form of multiple inheritance as well. A class " "definition with multiple base classes looks like this::" msgstr "파이썬은 다중 상속의 형태도 지원합니다. 여러 개의 베이스 클래스를 갖는 클래스 정의는 이런 식입니다::" #: ../../tutorial/classes.rst:633 msgid "" "class DerivedClassName(Base1, Base2, Base3):\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class DerivedClassName(Base1, Base2, Base3):\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:640 msgid "" "For most purposes, in the simplest cases, you can think of the search for" " attributes inherited from a parent class as depth-first, left-to-right, " "not searching twice in the same class where there is an overlap in the " "hierarchy. Thus, if an attribute is not found in " ":class:`!DerivedClassName`, it is searched for in :class:`!Base1`, then " "(recursively) in the base classes of :class:`!Base1`, and if it was not " "found there, it was searched for in :class:`!Base2`, and so on." msgstr "" "대부분의 목적상, 가장 간단한 경우에, 부모 클래스로부터 상속된 어트리뷰트들의 검색을 깊이 우선으로, 왼쪽에서 오른쪽으로, 계층 " "구조에서 겹치는 같은 클래스를 두 번 검색하지 않는 것으로 생각할 수 있습니다. 그래서, 어트리뷰트가 " ":class:`!DerivedClassName` 에서 발견되지 않으면, :class:`!Base1` 에서 찾고, 그다음 " "(재귀적으로) :class:`!Base1` 의 베이스 클래스들을 검색합니다. 거기에서도 발견되지 않으면, " ":class:`!Base2` 에서 찾고, 이런 식으로 계속합니다." #: ../../tutorial/classes.rst:647 msgid "" "In fact, it is slightly more complex than that; the method resolution " "order changes dynamically to support cooperative calls to :func:`super`." " This approach is known in some other multiple-inheritance languages as " "call-next-method and is more powerful than the super call found in " "single-inheritance languages." msgstr "" "사실, 이것보다는 약간 더 복잡합니다; 메서드 결정 순서는 :func:`super` 로의 협력적인 호출을 지원하기 위해 동적으로 " "변경됩니다. 이 접근법은 몇몇 다른 다중 상속 언어들에서 call-next-method 라고 알려져 있고, 단일 상속 언어들에서 " "발견되는 super 호출보다 더 강력합니다." #: ../../tutorial/classes.rst:653 msgid "" "Dynamic ordering is necessary because all cases of multiple inheritance " "exhibit one or more diamond relationships (where at least one of the " "parent classes can be accessed through multiple paths from the bottommost" " class). For example, all classes inherit from :class:`object`, so any " "case of multiple inheritance provides more than one path to reach " ":class:`object`. To keep the base classes from being accessed more than " "once, the dynamic algorithm linearizes the search order in a way that " "preserves the left-to-right ordering specified in each class, that calls " "each parent only once, and that is monotonic (meaning that a class can be" " subclassed without affecting the precedence order of its parents). Taken" " together, these properties make it possible to design reliable and " "extensible classes with multiple inheritance. For more detail, see " ":ref:`python_2.3_mro`." msgstr "" "동적인 순서가 필요한 이유는, 모든 다중 상속의 경우는 하나나 그 이상의 다이아몬드 관계 (적어도 부모 클래스 중 하나가 가장 바닥" " 클래스들로부터 여러 경로를 통해 액세스 되는 경우) 를 만들기 때문입니다. 예를 들어, 모든 클래스는 :class:`object`" " 를 계승하기 때문에, 모든 다중 상속은 :class:`object` 에 이르는 여러 경로를 제공합니다. 베이스 클래스들이 여러 번" " 액세스 되지 않게 하려고, 동적인 알고리즘이 검색 순서를 선형화하는데, 각 클래스에서 지정된 왼쪽에서 오른쪽으로 가는 순서를 " "보존하고, 각 부모를 오직 한 번만 호출하고, 단조적 (부모들의 우선순위에 영향을 주지 않으면서 서브 클래스를 만들 수 있다는 " "의미입니다) 이도록 만듭니다. 모두 함께 사용될 때, 이 성질들은 다중 상속으로 신뢰성 있고 확장성 있는 클래스들을 설계할 수 " "있도록 만듭니다. 더 자세한 내용은, :ref:`python_2.3_mro`\\를 보세요." #: ../../tutorial/classes.rst:670 msgid "Private Variables" msgstr "비공개 변수" #: ../../tutorial/classes.rst:672 msgid "" "\"Private\" instance variables that cannot be accessed except from inside" " an object don't exist in Python. However, there is a convention that is" " followed by most Python code: a name prefixed with an underscore (e.g. " "``_spam``) should be treated as a non-public part of the API (whether it " "is a function, a method or a data member). It should be considered an " "implementation detail and subject to change without notice." msgstr "" "객체 내부에서만 액세스할 수 있는 \"비공개\" 인스턴스 변수는 파이썬에 존재하지 않습니다. 하지만, 대부분의 파이썬 코드에서 " "따르고 있는 규약이 있습니다: 밑줄로 시작하는 이름은 (예를 들어, ``_spam``) API의 공개적이지 않은 부분으로 취급되어야" " 합니다 (그것이 함수, 메서드, 데이터 멤버중 무엇이건 간에). 구현 상세이고 통보 없이 변경되는 대상으로 취급되어야 합니다." #: ../../tutorial/classes.rst:682 msgid "" "Since there is a valid use-case for class-private members (namely to " "avoid name clashes of names with names defined by subclasses), there is " "limited support for such a mechanism, called :dfn:`name mangling`. Any " "identifier of the form ``__spam`` (at least two leading underscores, at " "most one trailing underscore) is textually replaced with " "``_classname__spam``, where ``classname`` is the current class name with " "leading underscore(s) stripped. This mangling is done without regard to " "the syntactic position of the identifier, as long as it occurs within the" " definition of a class." msgstr "" "클래스-비공개 멤버들의 올바른 사례가 있으므로 (즉 서브 클래스에서 정의된 이름들과의 충돌을 피하고자), :dfn:`이름 뒤섞기 " "(name mangling)` 라고 불리는 메커니즘에 대한 제한된 지원이 있습니다. ``__spam`` 형태의 (최소 두 개의 " "밑줄로 시작하고, 최대 한 개의 밑줄로 끝납니다) 모든 식별자는 ``_classname__spam`` 로 텍스트 적으로 치환되는데," " ``classname`` 은 현재 클래스 이름에서 앞에 오는 밑줄을 제거한 것입니다. 이 뒤섞기는 클래스 정의에 등장하는 이상, " "식별자의 문법적 위치와 무관하게 수행됩니다." #: ../../tutorial/classes.rst:693 msgid "" "The :ref:`private name mangling specifications ` " "for details and special cases." msgstr "자세한 내용과 특수한 사례는 :ref:`비공개 이름 뒤섞기 명세 `\\를 참조하세요." #: ../../tutorial/classes.rst:696 msgid "" "Name mangling is helpful for letting subclasses override methods without " "breaking intraclass method calls. For example::" msgstr "" "이름 뒤섞기는 클래스 내부의 메서드 호출을 방해하지 않고 서브 클래스들이 메서드를 재정의할 수 있도록 하는 데 도움을 줍니다. 예를" " 들어::" #: ../../tutorial/classes.rst:699 msgid "" "class Mapping:\n" " def __init__(self, iterable):\n" " self.items_list = []\n" " self.__update(iterable)\n" "\n" " def update(self, iterable):\n" " for item in iterable:\n" " self.items_list.append(item)\n" "\n" " __update = update # private copy of original update() method\n" "\n" "class MappingSubclass(Mapping):\n" "\n" " def update(self, keys, values):\n" " # provides new signature for update()\n" " # but does not break __init__()\n" " for item in zip(keys, values):\n" " self.items_list.append(item)" msgstr "" "class Mapping:\n" " def __init__(self, iterable):\n" " self.items_list = []\n" " self.__update(iterable)\n" "\n" " def update(self, iterable):\n" " for item in iterable:\n" " self.items_list.append(item)\n" "\n" " __update = update # 기존 update() 메서드의 비공개 사본\n" "\n" "class MappingSubclass(Mapping):\n" "\n" " def update(self, keys, values):\n" " # update() 에 새로운 서명을 제공하지만\n" " # __init__() 를 망가뜨리진 않습니다\n" " for item in zip(keys, values):\n" " self.items_list.append(item)" #: ../../tutorial/classes.rst:718 msgid "" "The above example would work even if ``MappingSubclass`` were to " "introduce a ``__update`` identifier since it is replaced with " "``_Mapping__update`` in the ``Mapping`` class and " "``_MappingSubclass__update`` in the ``MappingSubclass`` class " "respectively." msgstr "" "위의 예는 ``MappingSubclass``\\가 ``__update`` 식별자를 도입하더라도 작동합니다. ``Mapping`` " "클래스에서는 ``_Mapping__update``\\로 ``MappingSubclass`` 클래스에서는 " "``_MappingSubclass__update``\\로 각각 대체 되기 때문입니다." #: ../../tutorial/classes.rst:723 msgid "" "Note that the mangling rules are designed mostly to avoid accidents; it " "still is possible to access or modify a variable that is considered " "private. This can even be useful in special circumstances, such as in " "the debugger." msgstr "" "뒤섞기 규칙은 대체로 사고를 피하고자 설계되었다는 것에 주의하세요; 여전히 비공개로 취급되는 변수들을 액세스하거나 수정할 수 " "있습니다. 이것은 디버거와 같은 특별한 상황에서 쓸모 있기조차 합니다." #: ../../tutorial/classes.rst:727 msgid "" "Notice that code passed to ``exec()`` or ``eval()`` does not consider the" " classname of the invoking class to be the current class; this is similar" " to the effect of the ``global`` statement, the effect of which is " "likewise restricted to code that is byte-compiled together. The same " "restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as" " well as when referencing ``__dict__`` directly." msgstr "" "``exec()`` 나 ``eval()`` 로 전달된 코드는 호출하는 클래스의 클래스 이름을 현재 클래스로 여기지 않는다는 것에 " "주의하세요; 이것은 ``global`` 문의 효과와 유사한데, 효과가 함께 바이트-컴파일된 코드로 제한됩니다. 같은 제약이 " "``__dict__`` 를 직접 참조할 때뿐만 아니라, ``getattr()``, ``setattr()``, " "``delattr()`` 에도 적용됩니다." #: ../../tutorial/classes.rst:738 msgid "Odds and Ends" msgstr "잡동사니" #: ../../tutorial/classes.rst:740 msgid "" "Sometimes it is useful to have a data type similar to the Pascal " "\"record\" or C \"struct\", bundling together a few named data items. The" " idiomatic approach is to use :mod:`dataclasses` for this purpose::" msgstr "" "때로 몇몇 이름 붙은 데이터 항목들을 함께 묶어주는 파스칼의 \"record\" 나 C의 \"struct\" 와 유사한 데이터형을 " "갖는 것이 쓸모 있습니다. 이 경우 :mod:`dataclasses`\\를 사용하는 것이 일반적인 방법입니다::" #: ../../tutorial/classes.rst:744 msgid "" "from dataclasses import dataclass\n" "\n" "@dataclass\n" "class Employee:\n" " name: str\n" " dept: str\n" " salary: int" msgstr "" "from dataclasses import dataclass\n" "\n" "@dataclass\n" "class Employee:\n" " name: str\n" " dept: str\n" " salary: int" #: ../../tutorial/classes.rst:754 msgid "" ">>> john = Employee('john', 'computer lab', 1000)\n" ">>> john.dept\n" "'computer lab'\n" ">>> john.salary\n" "1000" msgstr "" ">>> john = Employee('john', 'computer lab', 1000)\n" ">>> john.dept\n" "'computer lab'\n" ">>> john.salary\n" "1000" #: ../../tutorial/classes.rst:760 msgid "" "A piece of Python code that expects a particular abstract data type can " "often be passed a class that emulates the methods of that data type " "instead. For instance, if you have a function that formats some data " "from a file object, you can define a class with methods " ":meth:`~io.TextIOBase.read` and :meth:`~io.TextIOBase.readline` that get " "the data from a string buffer instead, and pass it as an argument." msgstr "" "특정한 추상적인 데이터형을 기대하는 파이썬 코드 조각은, 종종 그 데이터형의 메서드를 흉내 내는 클래스를 대신 전달받을 수 " "있습니다. 예를 들어, 파일 객체로부터 데이터를 포맷하는 함수가 있을 때, 대신 문자열 버퍼에서 데이터를 읽는 메서드 " ":meth:`~io.TextIOBase.read` 와 :meth:`~io.TextIOBase.readline` 을 제공하는 클래스를" " 정의한 후 인자로 전달할 수 있습니다." #: ../../tutorial/classes.rst:772 msgid "" ":ref:`Instance method objects ` have attributes, too: " ":attr:`m.__self__ ` is the instance object with the " "method :meth:`!m`, and :attr:`m.__func__ ` is the " ":ref:`function object ` corresponding to the method." msgstr "" ":ref:`인스턴스 메서드 객체 `\\도 어트리뷰트를 갖습니다: :attr:`m.__self__ " "` 는 메서드 :meth:`!m` 과 결합한 인스턴스 객체이고, :attr:`m.__func__ " "` 는 메서드에 상응하는 :ref:`함수 객체 `\\입니다." #: ../../tutorial/classes.rst:782 msgid "Iterators" msgstr "이터레이터" #: ../../tutorial/classes.rst:784 msgid "" "By now you have probably noticed that most container objects can be " "looped over using a :keyword:`for` statement::" msgstr "지금쯤 아마도 여러분은 대부분의 컨테이너 객체들을 :keyword:`for` 문으로 루핑할 수 있음을 눈치챘을 것입니다::" #: ../../tutorial/classes.rst:787 #, python-brace-format msgid "" "for element in [1, 2, 3]:\n" " print(element)\n" "for element in (1, 2, 3):\n" " print(element)\n" "for key in {'one':1, 'two':2}:\n" " print(key)\n" "for char in \"123\":\n" " print(char)\n" "for line in open(\"myfile.txt\"):\n" " print(line, end='')" msgstr "" "for element in [1, 2, 3]:\n" " print(element)\n" "for element in (1, 2, 3):\n" " print(element)\n" "for key in {'one':1, 'two':2}:\n" " print(key)\n" "for char in \"123\":\n" " print(char)\n" "for line in open(\"myfile.txt\"):\n" " print(line, end='')" #: ../../tutorial/classes.rst:798 msgid "" "This style of access is clear, concise, and convenient. The use of " "iterators pervades and unifies Python. Behind the scenes, the " ":keyword:`for` statement calls :func:`iter` on the container object. The" " function returns an iterator object that defines the method " ":meth:`~iterator.__next__` which accesses elements in the container one " "at a time. When there are no more elements, :meth:`~iterator.__next__` " "raises a :exc:`StopIteration` exception which tells the :keyword:`!for` " "loop to terminate. You can call the :meth:`~iterator.__next__` method " "using the :func:`next` built-in function; this example shows how it all " "works::" msgstr "" "이런 스타일의 액세스는 명료하고, 간결하고, 편리합니다. 이터레이터를 사용하면 파이썬이 보편화하고 통합됩니다. 무대 뒤에서, " ":keyword:`for` 문은 컨테이너 객체에 대해 :func:`iter` 를 호출합니다. 이 함수는 메서드 " ":meth:`~iterator.__next__` 를 정의하는 이터레이터 객체를 돌려주는데, 이 메서드는 컨테이너의 요소들을 한 번에" " 하나씩 액세스합니다. 남은 요소가 없으면, :meth:`~iterator.__next__` 는 " ":exc:`StopIteration` 예외를 일으켜서 :keyword:`!for` 루프에 종료를 알립니다. :func:`next` " "내장 함수를 사용해서 :meth:`~iterator.__next__` 메서드를 호출할 수 있습니다; 이 예는 이 모든 것들이 어떻게" " 동작하는지 보여줍니다::" #: ../../tutorial/classes.rst:807 msgid "" ">>> s = 'abc'\n" ">>> it = iter(s)\n" ">>> it\n" "\n" ">>> next(it)\n" "'a'\n" ">>> next(it)\n" "'b'\n" ">>> next(it)\n" "'c'\n" ">>> next(it)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" " next(it)\n" "StopIteration" msgstr "" ">>> s = 'abc'\n" ">>> it = iter(s)\n" ">>> it\n" "\n" ">>> next(it)\n" "'a'\n" ">>> next(it)\n" "'b'\n" ">>> next(it)\n" "'c'\n" ">>> next(it)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" " next(it)\n" "StopIteration" #: ../../tutorial/classes.rst:823 msgid "" "Having seen the mechanics behind the iterator protocol, it is easy to add" " iterator behavior to your classes. Define an " ":meth:`~container.__iter__` method which returns an object with a " ":meth:`~iterator.__next__` method. If the class defines " ":meth:`!__next__`, then :meth:`!__iter__` can just return ``self``::" msgstr "" "이터레이터 프로토콜의 뒤에 있는 메커니즘을 살펴보면, 여러분의 클래스에 이터레이터 동작을 쉽게 추가할 수 있습니다. " ":meth:`~iterator.__next__` 메서드를 가진 객체를 돌려주는 :meth:`~container.__iter__` " "메서드를 정의합니다. 클래스가 :meth:`!__next__` 를 정의하면, :meth:`!__iter__` 는 그냥 " "``self`` 를 돌려줄 수 있습니다." #: ../../tutorial/classes.rst:828 msgid "" "class Reverse:\n" " \"\"\"Iterator for looping over a sequence backwards.\"\"\"\n" " def __init__(self, data):\n" " self.data = data\n" " self.index = len(data)\n" "\n" " def __iter__(self):\n" " return self\n" "\n" " def __next__(self):\n" " if self.index == 0:\n" " raise StopIteration\n" " self.index = self.index - 1\n" " return self.data[self.index]" msgstr "" "class Reverse:\n" " \"\"\"시퀀스를 역순으로 이터레이트하는 이터레이터.\"\"\"\n" " def __init__(self, data):\n" " self.data = data\n" " self.index = len(data)\n" "\n" " def __iter__(self):\n" " return self\n" "\n" " def __next__(self):\n" " if self.index == 0:\n" " raise StopIteration\n" " self.index = self.index - 1\n" " return self.data[self.index]" #: ../../tutorial/classes.rst:845 msgid "" ">>> rev = Reverse('spam')\n" ">>> iter(rev)\n" "<__main__.Reverse object at 0x00A1DB50>\n" ">>> for char in rev:\n" "... print(char)\n" "...\n" "m\n" "a\n" "p\n" "s" msgstr "" ">>> rev = Reverse('spam')\n" ">>> iter(rev)\n" "<__main__.Reverse object at 0x00A1DB50>\n" ">>> for char in rev:\n" "... print(char)\n" "...\n" "m\n" "a\n" "p\n" "s" #: ../../tutorial/classes.rst:860 msgid "Generators" msgstr "제너레이터" #: ../../tutorial/classes.rst:862 msgid "" ":term:`Generators ` are a simple and powerful tool for " "creating iterators. They are written like regular functions but use the " ":keyword:`yield` statement whenever they want to return data. Each time " ":func:`next` is called on it, the generator resumes where it left off (it" " remembers all the data values and which statement was last executed). " "An example shows that generators can be trivially easy to create::" msgstr "" ":term:`제너레이터 ` 는 이터레이터를 만드는 간단하고 강력한 도구입니다. 일반적인 함수처럼 작성되지만 값을" " 돌려주고 싶을 때마다 :keyword:`yield` 문을 사용합니다. 제너레이터에 :func:`next` 가 호출될 때마다, " "제너레이터는 떠난 곳에서 실행을 재개합니다 (모든 데이터 값들과 어떤 문장이 마지막으로 실행되었는지 기억합니다). 예는 제너레이터를" " 사소할 정도로 쉽게 만들 수 있음을 보여줍니다::" #: ../../tutorial/classes.rst:869 msgid "" "def reverse(data):\n" " for index in range(len(data)-1, -1, -1):\n" " yield data[index]" msgstr "" "def reverse(data):\n" " for index in range(len(data)-1, -1, -1):\n" " yield data[index]" #: ../../tutorial/classes.rst:875 msgid "" ">>> for char in reverse('golf'):\n" "... print(char)\n" "...\n" "f\n" "l\n" "o\n" "g" msgstr "" ">>> for char in reverse('golf'):\n" "... print(char)\n" "...\n" "f\n" "l\n" "o\n" "g" #: ../../tutorial/classes.rst:883 msgid "" "Anything that can be done with generators can also be done with class-" "based iterators as described in the previous section. What makes " "generators so compact is that the :meth:`~iterator.__iter__` and " ":meth:`~generator.__next__` methods are created automatically." msgstr "" "제너레이터로 할 수 있는 모든 것은 앞 절에서 설명했듯이 클래스 기반 이터레이터로도 할 수 있습니다. 제너레이터가 간단한 이유는 " ":meth:`~iterator.__iter__` 와 :meth:`~generator.__next__` 메서드가 저절로 만들어지기 " "때문입니다." #: ../../tutorial/classes.rst:888 msgid "" "Another key feature is that the local variables and execution state are " "automatically saved between calls. This made the function easier to " "write and much more clear than an approach using instance variables like " "``self.index`` and ``self.data``." msgstr "" "또 하나의 주요 기능은 지역 변수들과 실행 상태가 호출 간에 자동으로 보관된다는 것입니다. 이것은 ``self.index`` 나 " "``self.data`` 와 같은 인스턴스 변수를 사용하는 접근법에 비교해 함수를 쓰기 쉽고 명료하게 만듭니다." #: ../../tutorial/classes.rst:893 msgid "" "In addition to automatic method creation and saving program state, when " "generators terminate, they automatically raise :exc:`StopIteration`. In " "combination, these features make it easy to create iterators with no more" " effort than writing a regular function." msgstr "" "자동 메서드 생성과 프로그램 상태의 저장에 더해, 제너레이터가 종료할 때 자동으로 :exc:`StopIteration` 을 " "일으킵니다. 조합하면, 이 기능들이 일반 함수를 작성하는 것만큼 이터레이터를 만들기 쉽게 만듭니다." #: ../../tutorial/classes.rst:902 msgid "Generator Expressions" msgstr "제너레이터 표현식" #: ../../tutorial/classes.rst:904 msgid "" "Some simple generators can be coded succinctly as expressions using a " "syntax similar to list comprehensions but with parentheses instead of " "square brackets. These expressions are designed for situations where the " "generator is used right away by an enclosing function. Generator " "expressions are more compact but less versatile than full generator " "definitions and tend to be more memory friendly than equivalent list " "comprehensions." msgstr "" "간단한 제너레이터는 리스트 컴프리헨션과 비슷하지만, 대괄호 대신 괄호를 사용하는 문법을 사용한 표현식으로 간결하게 코딩할 수 " "있습니다. 이 표현식들은 둘러싸는 함수가 제너레이터를 즉시 사용하는 상황을 위해 설계되었습니다. 제너레이터 표현식은 완전한 " "제너레이터 정의보다 간결하지만, 융통성은 떨어지고, 비슷한 리스트 컴프리헨션보다 메모리를 덜 쓰는 경향이 있습니다." #: ../../tutorial/classes.rst:911 msgid "Examples::" msgstr "예::" #: ../../tutorial/classes.rst:913 msgid "" ">>> sum(i*i for i in range(10)) # sum of squares\n" "285\n" "\n" ">>> xvec = [10, 20, 30]\n" ">>> yvec = [7, 5, 3]\n" ">>> sum(x*y for x,y in zip(xvec, yvec)) # dot product\n" "260\n" "\n" ">>> unique_words = set(word for line in page for word in line.split())\n" "\n" ">>> valedictorian = max((student.gpa, student.name) for student in " "graduates)\n" "\n" ">>> data = 'golf'\n" ">>> list(data[i] for i in range(len(data)-1, -1, -1))\n" "['f', 'l', 'o', 'g']" msgstr "" ">>> sum(i*i for i in range(10)) # 제곱의 합\n" "285\n" "\n" ">>> xvec = [10, 20, 30]\n" ">>> yvec = [7, 5, 3]\n" ">>> sum(x*y for x,y in zip(xvec, yvec)) # 내적\n" "260\n" "\n" ">>> unique_words = set(word for line in page for word in line.split())\n" "\n" ">>> valedictorian = max((student.gpa, student.name) for student in " "graduates)\n" "\n" ">>> data = 'golf'\n" ">>> list(data[i] for i in range(len(data)-1, -1, -1))\n" "['f', 'l', 'o', 'g']" #: ../../tutorial/classes.rst:932 msgid "Footnotes" msgstr "각주" #: ../../tutorial/classes.rst:933 msgid "" "Except for one thing. Module objects have a secret read-only attribute " "called :attr:`~object.__dict__` which returns the dictionary used to " "implement the module's namespace; the name ``__dict__`` is an attribute " "but not a global name. Obviously, using this violates the abstraction of " "namespace implementation, and should be restricted to things like post-" "mortem debuggers." msgstr "" "한 가지만 제외하고. 모듈 객체는 :attr:`~object.__dict__` 라고 불리는 비밀스러운 읽기 전용 어트리뷰트를 " "갖는데, 모듈의 이름 공간을 구현하는데 사용하는 딕셔너리를 돌려줍니다; 이름 ``__dict__`` 는 어트리뷰트 이지만 전역 " "이름은 아닙니다. 명백하게, 이것을 사용하는 것은 이름 공간 구현의 추상화를 파괴하는 것이고, 사후 디버거와 같은 것들로만 " "제한되어야 합니다." #: ../../tutorial/classes.rst:343 msgid "object" msgstr "객체" #: ../../tutorial/classes.rst:343 msgid "method" msgstr "메서드" #: ../../tutorial/classes.rst:679 msgid "name" msgstr "이름" #: ../../tutorial/classes.rst:679 msgid "mangling" msgstr "뒤섞기"