input을 통해 입력값을 받고 sum함수로 1부터 입력한 값까지 합하고 print로 결과를 출력하도록 하겠습니다😀 반복문인 for문으로 1부터 입력받는 숫자(n)까지 반복하도록 하고 실행할 문장은 1부터 n까지 각각의 숫자를 더하는 방식으로 방향을 잡았습니다.
한 줄씩 살펴보겠습니다. n이라는 변수에 input함수로 입력값을 받을 수 있게 했고 input함수는 문자열로 입력받기 때문에 int함수를 이용해 정수로 변환시켰습니다. sum이라는 변수에 0을 지정해 int 속성의 정수임을 선언합니다.
for문의 range함수를 이용해 1부터 입력받은 n까지의 합을 구할 범위를 지정합니다. range() 의 괄호 안에 첫 번째 값은 변수에 처음 입력될 값이고 두 번째 값은 변수에 입력되는 순간 반복을 멈추기 때문에 (1, n) 이 아닌 (1, n+1) 로 작성해야 합니다. ※ for문의 사용법이 혼동된다면 아래 링크를 참고해주세요! https://ho-ding.tistory.com/13 1부터 입력값인 n까지의 숫자를 하나씩 꺼낸 변수 i 를 변수 sum에 더해줍니다. 더해진 값을 print 함수로 출력합니다. 내장 함수¶파이썬 인터프리터에는 항상 사용할 수 있는 많은 함수와 형이 내장되어 있습니다. 여기에서 알파벳 순으로 나열합니다.
숫자의 절댓값을 돌려줍니다. 인자는 정수, 실수 또는 Return an asynchronous iterator for an asynchronous
iterable. Equivalent to calling Note: Unlike 버전 3.10에 추가. all(iterable)¶iterable 의 모든 요소가 참이면 (또는 iterable 이 비어있으면) def all(iterable): for element in iterable: if not element: return False return Trueawaitable anext(async_iterator)¶ awaitableanext(async_iterator, default) When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted. This is the async variant of the This calls the
버전 3.10에 추가. any(iterable)¶iterable 의 요소 중 어느 하나라도 참이면 def any(iterable): for element in iterable: if element: return True return Falseascii(object)¶ As 정수를 “0b” 가 앞에 붙은 이진 문자열로 변환합니다. 결과는 올바른 파이썬 표현식입니다. x 가 파이썬 >>> bin(3) '0b11' >>> bin(-10) '-0b1010' If the prefix “0b” is desired or not, you can use either of the following ways. >>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') 자세한 내용은 Return a Boolean value, i.e. one of 버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다. breakpoint(*args, **kws)¶This function drops you into the debugger at the call site. Specifically, it calls
버전 3.7에 추가. class bytearray(source=b'') classbytearray(source, encoding) class bytearray(source, encoding, errors)새로운 바이트 배열을 돌려줍니다. 선택적 source 매개변수는 몇 가지 다른 방법으로 배열을 초기화하는 데 사용할 수 있습니다:
인자가 없으면 크기 0의 배열이 만들어집니다. 바이너리 시퀀스 형 — bytes, bytearray, memoryview와 바이트 배열 객체 도 보세요. classbytes(source=b'') class bytes(source, encoding) classbytes(source, encoding, errors)Return a new “bytes” object which is an immutable sequence of integers in the range 따라서 생성자 인자는 바이트열 객체는 리터럴을 사용하여 만들 수도 있습니다 (문자열과 바이트열 리터럴 를 보세요). 바이너리 시퀀스 형 — bytes, bytearray, memoryview, 바이트열 객체 및 바이트열 과 바이트 배열 연산 도 보세요. callable(object)¶object 인자가 콜러블인 것처럼 보이면
버전 3.2에 추가: 이 함수는 파이썬 3.0에서 먼저 제거된 다음 파이썬 3.2에서 다시 도입했습니다. chr(i)¶유니코드 코드 포인트가 정수 i 인 문자를 나타내는 문자열을 돌려줍니다. 예를 들어, 인자의 유효 범위는 0에서
1,114,111(16진수로 0x10FFFF)까지입니다. i 가 이 범위 밖에 있을 때 메서드를 클래스 메서드로 변환합니다. A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: @classmethod def f(cls, arg1, arg2): ...
클래스 메서드는 클래스 ( 클래스 메서드는 C++ 또는 자바의 정적 메서드와 다릅니다. 그것들을 원하면, 이 섹션의 버전 3.9에서 변경: 클래스 메서드는 이제
버전 3.10에서 변경: Class methods now inherit the method attributes ( source 를 코드 또는 AST 객체로 컴파일합니다. 코드 객체는 filename 인자는 코드를 읽은 파일을 제공해야 합니다; 파일에서 읽지 않으면 인식 가능한 값을 전달합니다 ( mode 인자는 컴파일해야 하는 코드 종류를 지정합니다; source 가 문장의 시퀀스로 구성되어 있다면 선택적
인자 flags 와 dont_inherit 는 어떤 컴파일러 옵션이 활성화되어야 하고 어떤 퓨처 기능이 허락되어야 하는지 제어합니다. 둘 다 제공되지 않는 경우 (또는 둘 다 0의 경우), 코드는 컴파일러 옵션과 퓨처 문은 여러 개의 옵션을 지정하기 위해 비트 OR 될 수 있는 비트에 의해 지정됩니다. 주어진 퓨처 기능을 지정하는 데 필요한 비트 필드는 인자 optimize 는 컴파일러의 최적화 수준을 지정합니다; 기본값 이 함수는 컴파일된 소스가 올바르지 않으면 파이썬 코드를 AST 표현으로 파싱하려면,
참고
경고 파이썬의 AST 컴파일러에서 스택 깊이 제한으로 인해, AST 객체로 컴파일할 때 충분히 크고 복잡한 문자열로 파이썬 인터프리터가 크래시를 일으키도록 만들 수 있습니다. 버전 3.2에서 변경: Allowed use of Windows and Mac newlines. Also, input in 버전 3.5에서 변경: 이전에는, source 에서 널 바이트가 발견될 때 버전 3.8에 추가: 이제 real + imag*1j 값을 가진 복소수를 돌려주거나 문자열 또는 숫자를 복소수로 변환합니다. 첫 번째 매개변수가 문자열이면 복소수로 해석되며, 두 번째 매개변수 없이 함수를 호출해야 합니다. 두 번째 매개변수는 결코 문자열 일 수 없습니다. 각 인자는 모든 (복소수를 포함한) 숫자 형이 될 수 있습니다. imag 가 생략되면 기본값은 0이고, 생성자는 일반적인 파이썬 객체 참고 문자열을 변환할 때, 문자열은 중앙의 복소수 형은 숫자 형 — int, float, complex 에서 설명합니다. 버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다. 버전 3.8에서 변경: This is a relative of 새 딕셔너리를 만듭니다. 다른 컨테이너의 경우
인자가 없으면, 현재 지역 스코프에 있는 이름들의 리스트를 돌려줍니다. 인자가 있으면, 해당 객체에 유효한 어트리뷰트들의 리스트를 돌려주려고 시도합니다. 객체에 If the object does not provide 기본
결과 리스트는 알파벳 순으로 정렬됩니다. 예를 들어: >>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter'] 참고
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as 열거 객체를 돌려줍니다. iterable 은 시퀀스, 이터레이터 또는 이터레이션을 지원하는 다른 객체여야 합니다.
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 다음과 동등합니다: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1eval(expression, /, globals=None, locals=None)¶ 인자는 문자열 및 선택적 globals 및 locals다. 제공된 경우, globals 는 딕셔너리여야 합니다. 제공되는 경우, locals 는 모든 매핑 객체가 될 수 있습니다. The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key 반환 값은 계산된 표현식의 결과입니다. 문법 에러는 예외로 보고됩니다. 예: >>> x = 1 >>> eval('x+1') 2 This function can also be used to execute arbitrary code objects (such as those created by Hints: dynamic execution of statements is supported by the If the given source is a string, then leading and trailing spaces and tabs are stripped. 리터럴 만 포함 된 표현식의 값을 안전하게 구할 수 있는 함수
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).
1 If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section 파일 입력 in the Reference Manual). Be aware that the
In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. globals 딕셔너리가 The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.
참고 기본 locals 는 아래 함수 버전 3.11에서 변경: Added the closure parameter. filter(function, iterable)¶function 이 참을 돌려주는 iterable 의 요소들로 이터레이터를 구축합니다. iterable 은 시퀀스, 이터레이션을 지원하는 컨테이너 또는 이터레이터 일 수 있습니다. function 이
function
이 거짓을 돌려주는 iterable 의 요소들을 돌려주는 상보적인 함수는 숫자 또는 문자열 x 로 부터 실수를 만들어 돌려줍니다. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may
be sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" digitpart ::= Here 그렇지 않으면, 인자가 정수 또는 실수면 (파이썬의 부동 소수점 정밀도 내에서) 같은 값을 가진 실수가 반환됩니다. 인자가 파이썬 float 범위를 벗어나면, 일반적인 파이썬 객체 인자가 주어지지 않으면, 예: >>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf float 형은 숫자 형 — int, float, complex 에 설명되어 있습니다. 버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다. 버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다. 버전 3.8에서 변경: Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: 포맷 명세 미니 언어. 기본 format_spec 은 빈 문자열이며 일반적으로
버전 3.4에서 변경: 새
다른 컨테이너의 경우
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, 참고 Since private name
mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called. hasattr(object, name)¶인자는 객체와 문자열입니다. 문자열이 객체의 속성 중 하나의 이름이면 결과는 객체의 해시값을 돌려줍니다 (해시가 있는 경우). 해시값은 정수다. 딕셔너리 조회 중에 딕셔너리 키를 빨리 비교하는 데 사용됩니다. 같다고 비교되는 숫자 값은 같은 해시값을 갖습니다 (1과 1.0의 경우와 같이 형이 다른 경우조차도 그렇습니다). 참고 커스텀 내장 도움말 시스템을 호출합니다. (이 함수는 대화형 사용을 위한 것입니다.) 인자가 제공되지 않으면, 인터프리터 콘솔에서 대화형 도움말 시스템이 시작됩니다. 인자가 문자열이면 문자열은 모듈, 함수, 클래스, 메서드, 키워드 또는 설명서 주제의 이름으로 조회되고, 도움말 페이지가 콘솔에 인쇄됩니다. 인자가 다른 종류의 객체면, 객체에 대한 도움말 페이지가 만들어집니다. Note that if a slash(/) appears in the parameter list of a function when invoking
이 함수는
버전 3.4에서 변경: 정수를 “0x” 접두사가 붙은 소문자 16진수 문자열로 변환합니다.
x 가 파이썬 >>> hex(255) '0xff' >>> hex(-42) '-0x2a' 정수를 대문자 또는 소문자 16진수로, 접두사가 있거나 없는 형태로 변환하려면 다음 방법의 하나를 사용할 수 있습니다: >>> '%#x' % 255, '%x' % 255, '%X' % 255 ('0xff', 'ff', 'FF') >>> format(255, '#x'), format(255, 'x'), format(255, 'X') ('0xff', 'ff', 'FF') >>> f'{255:#x}', f'{255:x}', f'{255:X}' ('0xff', 'ff', 'FF') 자세한 내용은 16진수 문자열을 진수 16을 사용해서 정수로 변환하려면
참고 float에 대한 16진수 문자열 표현을 얻으려면, 객체의 “아이덴티티”를 돌려준다. 이것은 객체의 수명 동안 유일하고 바뀌지 않음이 보장되는 정수입니다. 수명이 겹치지 않는 두 개의 객체는 같은 CPython 구현 상세: This is the address of the object in memory.
prompt 인자가 있으면, 끝에 개행 문자를 붙이지
않고 표준 출력에 씁니다. 그런 다음 함수는 입력에서 한 줄을 읽고, 문자열로 변환해서 (줄 끝의 줄 바꿈 문자를 제거한다) 돌려줍니다. EOF를 읽으면 >>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
숫자 나 문자열 x 로 부터 만들어진 정수 객체를 돌려줍니다. 인자가 주어지지 않으면 x 가 숫자가 아니거나 base 가 주어지면, x 는 문자열,
정수 형은 숫자 형 — int, float, complex 에 설명되어 있습니다. 버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다. 버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다. 버전 3.8에서 변경: 버전 3.11에서 변경: The delegation to 버전 3.11에서 변경: Return 버전 3.10에서 변경: classinfo can be a Union Type. issubclass(class, classinfo)¶Return 버전 3.10에서 변경: classinfo can be a Union Type. iter(object)¶ iter(object, sentinel)Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol
(the 이터레이터 형 도 보세요. 두 번째 형태의 from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)len(s)¶ 객체의 길이 (항목 수)를 돌려줍니다. 인자는 시퀀스 (문자열, 바이트열, 튜플, 리스트 또는 range 같은) 또는 컬렉션 (딕셔너리, 집합 또는 불변 집합 같은) 일 수 있습니다. classlist classlist(iterable)함수이기보다, 리스트 와
시퀀스 형 — list, tuple, range 에 문서화 된 것처럼, 현재 지역 심볼 테이블을 나타내는
딕셔너리를 갱신하고 돌려줍니다. 참고 이 딕셔너리의 내용은 수정해서는 안 됩니다. 변경 사항은 인터프리터가 사용하는 지역 및 자유 변수의 값에 영향을 미치지 않을 수 있습니다. map(function, iterable, *iterables)¶Return an iterator that applies function to every item of iterable, yielding
the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see iterable 에서 가장 큰 항목이나 두 개 이상의 인자 중 가장 큰 것을 돌려줍니다. 하나의 위치 인자가 제공되면, 그것은 이터러블 이어야 합니다. iterable에서 가장 큰 항목을 돌려줍니다. 두 개 이상의 위치 인자가 제공되면, 위치 인자 중 가장 큰 것을 돌려줍니다. 선택적 키워드-전용 인자가 두 개 있습니다. key 인자는 여러 항목이 최댓값이면, 함수는 처음 만난 항목을 돌려줍니다. 이것은 버전 3.4에 추가: default 키워드-전용 인자. 버전 3.8에서 변경: key는 지정된 인자로부터 만들어진 “메모리 뷰” 객체를 돌려줍니다. 자세한 정보는 메모리 뷰 를 보세요. min(iterable, *, key=None)¶ min(iterable, *, default, key=None) min(arg1, arg2, *args, key=None)iterable 에서 가장 작은 항목이나 두 개 이상의 인자 중 가장 작은 것을 돌려줍니다. 하나의 위치 인자가 제공되면, 그것은 이터러블 이어야 합니다. iterable에서 가장 작은 항목을 돌려줍니다. 두 개 이상의 위치 인자가 제공되면, 위치 인자 중 가장 작은 것을 돌려줍니다. 선택적 키워드-전용 인자가 두 개 있습니다. key 인자는 여러 항목이 최솟값이면, 함수는 처음 만난 항목을 돌려줍니다. 이것은 버전 3.4에 추가: default 키워드-전용 인자. 버전 3.8에서 변경: key는 Retrieve the next item from the
iterator by calling its Return a new featureless object. 정수를 “0o”로 시작하는 8진수 문자열로 변환합니다. 결과는 올바른 파이썬 표현식입니다. x 가 파이썬 >>> oct(8) '0o10' >>> oct(-56) '-0o70' If you want to convert an integer number to an octal string either with the prefix “0o” or not, you can use either of the following ways. >>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12') 자세한 내용은 file 을 열고 해당
파일 객체 를 돌려줍니다. 파일을 열 수 없으면, file is a
path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to mode is an optional string that specifies the mode in which the file is
opened. It defaults to
The default mode is 개요 에서 언급했듯이, 파이썬은 바이너리와 텍스트 I/O를 구별합니다. 바이너리 모드 (mode 인자에 참고 파이썬은 하위 운영 체제의 텍스트 파일 개념에 의존하지 않습니다. 모든 처리는 파이썬 자체에 의해 수행되므로 플랫폼에 독립적입니다. buffering is an optional
integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever
errors 는 인코딩 및 디코딩 에러를 처리하는 방법을 지정하는 선택적 문자열입니다. 바이너리 모드에서는 사용할 수 없습니다. 다양한 표준 에러 처리기가 제공됩니다 (에러 처리기 에 나열됩니다). 하지만,
newline determines how to parse newline characters from the stream. It
can be
If closefd is 콜러블을 opener 로 전달하여 커스텀 오프너를 사용할 수 있습니다. 파일 객체를 위한 하위 파일 디스크립터는 opener 를 (file, flags) 로 호출해서 얻습니다. opener 는 열린 파일 디스크립터를 반환해야 합니다 (opener 에 새로 만들어진 파일은 상속 불가능 합니다. 다음 예는 주어진 디렉터리에 상대적인 파일을 열기 위해 >>> import os >>> dir_fd = os.open('somedir', os.O_RDONLY) >>> def opener(path, flags): ... return os.open(path, flags, dir_fd=dir_fd) ... >>> with open('spamspam.txt', 'w', opener=opener) as f: ... print('This will be written to somedir/spamspam.txt', file=f) ... >>> os.close(dir_fd) # don't leak a file descriptor
See also the file handling modules, such as
버전 3.3에서 변경:
버전 3.4에서 변경:
버전 3.5에서 변경:
버전 3.11에서 변경: The 하나의 유니코드 문자를 나타내는 문자열이 주어지면 해당 문자의 유니코드 코드 포인트를 나타내는 정수를 돌려줍니다. 예를 들어, base 의 exp 거듭제곱을 돌려줍니다; mod 가 있는 경우, base 의 exp 거듭제곱의 모듈로 mod 를 돌려줍니다 ( The arguments must have numeric types. With mixed operand
types, the coercion rules for binary arithmetic operators apply. For
다음은 >>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True 버전 3.8에서 변경: 버전 3.8에서 변경: 키워드 인자를 허용합니다. 이전에는, 위치 인자만 지원되었습니다. print(*objects, sep=' ', end='\n', file=None, flush=False)¶Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments. 모든 비 키워드 인자는 file 인자는 Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed. 버전 3.3에서 변경: flush 키워드 인자가 추가되었습니다. classproperty(fget=None, fset=None, fdel=None, doc=None)¶프로퍼티 어트리뷰트를 돌려줍니다. fget 은 어트리뷰트 값을 얻는 함수입니다. fset 은 어트리뷰트 값을 설정하는 함수입니다. fdel 은 어트리뷰트 값을 삭제하는 함수입니다. 그리고 doc 은 어트리뷰트의 독스트링을 만듭니다. 전형적인 사용은 관리되는 어트리뷰트 class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") If c is an instance of C, 주어진 경우, doc 은 프로퍼티 어트리뷰트의 독스트링이 됩니다. 그렇지 않으면, fget 의 독스트링(있는 경우)이 복사됩니다. 이렇게 하면 class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
프로퍼티 객체는 데코레이터로 사용할 수 있는 class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x 이 코드는 첫 번째 예제와 정확히 동등합니다. 추가적인 함수들에 원래 프로퍼티(이 경우
반환된 프로퍼티 객체는 생성자 인자에 해당하는 버전 3.5에서 변경: 이제 프로퍼티 개체의 독스트링이 쓰기 가능합니다. classrange(stop) class range(start, stop, step=1)함수라기보다, Return a string containing a printable representation of an object. For many types, this function
makes an attempt to return a string that would yield an object with the same value when passed to 역 이터레이터 를 돌려줍니다. seq 는 number 를 소수점 다음에 ndigits 정밀도로 반올림한 값을 돌려줍니다. ndigits 가 생략되거나 For the built-in types supporting
일반적인 파이썬 객체 참고 float에 대한 새
다른 컨테이너의 경우 내장
This is the counterpart of name need not be a Python identifier as defined in
식별자와 키워드 unless the object chooses to enforce that, for example in a custom 참고 Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name
in order to set it with Return a slice object representing the set of indices specified by iterable 의 항목들로 새 정렬된 리스트를 돌려줍니다. 키워드 인자로만 지정해야 하는 두 개의 선택적 인자가 있습니다. key 는 하나의 인자를 받는 함수를 지정하는데, iterable의 각 요소들로부터 비교 키를 추출하는 데 사용됩니다 (예를 들어, reverse 는 논리값입니다.
예전 스타일의 cmp 함수를 key 함수로 변환하려면 내장 The sort algorithm uses only 정렬 예제와 간단한 정렬 자습서는 정렬 HOW TO 를 보세요. @staticmethod¶메서드를 정적 메서드로 변환합니다. 정적 메서드는 묵시적인 첫 번째 인자를 받지 않습니다. 정적 메서드를 선언하려면, 이 관용구를 사용하세요: class C: @staticmethod def f(arg1, arg2, ...): ...
A static method can be called either on the class (such as Static methods in Python are similar to those found in Java or C++. Also, see 모든 데코레이터와 마찬가지로, def regular_function(): ... class C: method = staticmethod(regular_function) 정적 메서드에 대한 더 자세한 정보는, 표준형 계층을 참조하세요. 버전 3.10에서 변경: Static methods now inherit the method attributes ( object 의
start 및 iterable 의 항목들을 왼쪽에서 오른쪽으로 합하고 합계를 돌려줍니다. iterable 의 항목은 일반적으로 숫자며 시작 값은 문자열이 될 수 없습니다. 어떤 경우에는 버전 3.8에서 변경: start 매개 변수는 키워드 인자로만 지정될 수 있습니다. class super¶ classsuper(type, object_or_type=None)메서드 호출을 type 의 부모나 형제 클래스에 위임하는 프락시 객체를 돌려줍니다. 이는 클래스에서 재정의된 상속 된 메서드를 액세스할 때 유용합니다. The object_or_type determines the method resolution order to be searched. The search starts from the class right after the type. For example, if The 두 번째 인자가 생략되면, 반환되는 슈퍼 객체는 연결되지 않았습니다(unbound). 두 번째 인자가 객체면, super 에는 두 가지 일반적인 사용 사례가 있습니다. 단일 상속 클래스 계층 구조에서는, super 를 사용하여 명시적으로 이름을 지정하지 않고 부모 클래스를 참조할 수 있으므로, 코드를 더 유지 관리하기 쉽게 만들 수 있습니다. 이 사용은 다른 프로그래밍 언어에서 super 를 쓰는 것과 매우 유사합니다. The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime). 두 경우 모두, 일반적인 슈퍼 클래스 호출은 이런 식입니다: class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg) 메서드 조회 외에,
또한, 인자가 없는 형식을 제외하고는,
함수이기보다,
인자 하나의 경우, object 의 형을 돌려줍니다. 반환 값은 형 객체며 일반적으로 객체의 형을 검사하는 데는 세 개의
인자를 주는 경우, 새 형 객체를 돌려줍니다. 이것은 본래 >>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1)) 형 객체를 보세요. 세 인자 형식에 제공된 키워드 인자는 클래스 정의의 (metaclass 를 제외한) 키워드와 같은 방식으로 적절한 메타 클래스 장치(일반적으로 클래스 생성 커스터마이제이션 도 보세요. 버전 3.6에서 변경: 모듈, 클래스, 인스턴스 또는 모듈 및 인스턴스와 같은 객체는 업데이트 가능한
인자가 없으면,
객체가 지정되었지만 Iterate over several iterables in parallel, producing tuples with an item from each one. Example: >>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice') More formally: Another way to think of
One thing to consider is that the iterables passed to
Edge cases: With a single iterable argument, Tips and tricks:
버전 3.10에서 변경:
Added the 이 함수는 The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the
names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the level 은 절대 또는 상대 임포트를 사용할지를 지정합니다. name 변수가 예를 들어, 문장
spam = __import__('spam', globals(), locals(), [], 0) 문장 spam = __import__('spam.ham', globals(), locals(), [], 0) 여기에서 반면에, 문장 _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage 여기서 단순히 이름으로 모듈을 임포트 하기 원한다면 (잠재적으로 패키지 내에서), 버전 3.3에서 변경: 음수 level 은 더 지원되지 않습니다 (기본값도 0으로 변경합니다). 버전 3.9에서 변경: 명령 줄 옵션
각주 1파서는 유닉스 스타일의 줄 종료 규칙만 받아들이는 것에 주의하세요. 파일에서 코드를 읽는 경우, 줄 넘김 변환 모드를 사용해서 윈도우나 맥 스타일 줄 넘김을 변환해야 합니다. |