3. ë°ì´í° 모ë¸Â¶
3.1. ê°ì²´, ê°, í¶
Objects are Pythonâs abstraction for data. All data in a Python program is represented by objects or by relations between objects. Even code is represented by objects.
Every object has an identity, a type and a value. An objectâs identity never
changes once it has been created; you may think of it as the objectâs address in
memory. The is operator compares the identity of two objects; the
id() function returns an integer representing its identity.
CPython ì ê²½ì°, id(x) ë x ê° ì ì¥ë ë©ëª¨ë¦¬ì 주ìì
ëë¤.
ê°ì²´ì íì ê°ì²´ê° ì§ìíë ì°ì°ë¤ì ì ìíê³ (ì를 ë¤ì´, â길ì´ë¥¼ ê°ê³ ìë?â) ê·¸ íì ê°ì²´ë¤ì´ ê°ì§ ì ìë ê°ë¥í ê°ë¤ì ì ìí©ëë¤. type() í¨ìë ê°ì²´ì í(ì´ê² ìì ê°ì²´ë¤)ì ëë ¤ì¤ëë¤. ìì´ë´í°í°ì ë§ì°¬ê°ì§ë¡, ê°ì²´ì í (type) ìì ë³ê²½ëì§ ììµëë¤. [1]
ì´ë¤ ê°ì²´ë¤ì ê° ì ë³ê²½í ì ììµëë¤. ê°ì ë³ê²½í ì ìë ê°ì²´ë¤ì ê°ë³(mutable) ì´ë¼ê³ í©ëë¤. ì¼ë¨ ë§ë¤ì´ì§ íì ê°ì ë³ê²½í ì ìë ê°ì²´ë¤ì ë¶ë³(immutable) ì´ë¼ê³ í©ëë¤. (ê°ë³ ê°ì²´ì ëí 참조를 ì ì¥íê³ ìë ë¶ë³ 컨í ì´ëì ê°ì ê°ë³ ê°ì²´ì ê°ì´ ë³í ë ë³ê²½ëë¤ê³ ë³¼ ìë ììµëë¤; íì§ë§ ì ì¥íê³ ìë ê°ì²´ë¤ì ì§í©ì´ ë°ë ì ìì¼ë¯ë¡ 컨í ì´ëë ì¬ì í ë¶ë³ì´ë¼ê³ ì¬ê²¨ì§ëë¤. ë°ë¼ì ë¶ë³ì±ì ìë°íê²ë ë³ê²½ ë¶ê°ë¥í ê°ì ê°ë ê²ê³¼ë ë¤ë¦ ëë¤. ì¢ ë 미ë¬í©ëë¤.) ê°ì²´ì ê°ë³ì±(mutability)ì ê·¸ê²ì íì ìí´ ê²°ì ë©ëë¤; ì를 ë¤ì´ ì«ì, 문ìì´, íí(tuple)ì ë¶ë³ì´ì§ë§, ëì ë리(dictionary) ì 리ì¤í¸(list)ë ê°ë³ì ëë¤.
ê°ì²´ë ê²°ì½ ëª ìì ì¼ë¡ íê´´ëì§ ììµëë¤; ë 참조ëì§ ìì ë(unreachable) ê°ë¹ì§ ìê±°(garbage collect)ë©ëë¤. 구íì´ ê°ë¹ì§ ì거를 ì§ì°ìí¤ê±°ë ìì ìëµíë ê²ì´ íë½ë©ëë¤ â ìì§ ì°¸ì¡°ëë ê°ì²´ë¤ì ìê±°íì§ ìë ì´ì ê°ë¹ì§ ìê±°ê° ì´ë¤ ìì¼ë¡ 구íëëì§ë 구íì íì§ ë¬¸ì ì ëë¤.
CPython ì íì¬ ì°¸ì¡° íì ê³ì°(reference-counting) ë°©ìì ì¬ì©íëë°, (ì í ì¬íì¼ë¡) ìíì ì¼ë¡ ì°ê²°ë ê°ë¹ì§ì ì§ì°ë ê°ì§ê° ì¶ê°ë©ëë¤. ì´ ë°©ë²ì¼ë¡ ëë¶ë¶ ê°ì²´ë¥¼ ì°¸ì¡°ê° ì ê±°ëìë§ì ìê±°í ì ììµëë¤. íì§ë§ ìí ì°¸ì¡°ê° ìë ê°ë¹ì§ë¤ì ìê±°íë¤ë ë³´ì¥ì ììµëë¤. ìíì ê°ë¹ì§ ìê±°ì ì ì´ì ê´í ì ë³´ë gc 모ë 문ì를 참조íë©´ ë©ëë¤. ë¤ë¥¸ 구íë¤ì ë¤ë¥¸ ìì¼ë¡ ëìíê³ , CPython ë ë³ê²½ë ì ììµëë¤. ì°¸ì¡°ê° ì ê±°ë ë ì¦ê°ì ì¼ë¡ íì´ë리ì ì´ì
(finalization)ëë ê²ì ìì¡´íì§ ë§ìì¼ í©ëë¤ (ê·¸ëì íì íì¼ì ëª
ìì ì¼ë¡ ë«ì주ì´ì¼ í©ëë¤).
Note that the use of the implementationâs tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a tryâ¦except statement may keep
objects alive.
Some objects contain references to âexternalâ resources such as open files or
windows. It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a close() method. Programs are strongly recommended to explicitly
close such objects. The tryâ¦finally statement
and the with statement provide convenient ways to do this.
ì´ë¤ ê°ì²´ë¤ì ë¤ë¥¸ ê°ì²´ì ëí 참조를 í¬í¨íê³ ììµëë¤. ì´ë° ê²ë¤ì 컨í ì´ë(container) ë¼ê³ ë¶ë¦ ëë¤. íí, 리ì¤í¸, ëì ë리ë±ì´ 컨í ì´ëì ìì ëë¤. ì´ ì°¸ì¡°ë¤ì 컨í ì´ëì ê°ì ì¼ë¶ì ëë¤. ëë¶ë¶ì, ì°ë¦¬ê° 컨í ì´ëì ê°ì ë ¼í ëë, ë¤ì´ìë ê°ì²´ë¤ì ìì´ë´í°í° ë³´ë¤ë ê°ì ë°ì§ëë¤. íì§ë§, 컨í ì´ëì ê°ë³ì±ì ëí´ ë ¼í ëë ì§ì ê°ì§ ê°ì²´ë¤ì ìì´ë´í°í°ë§ì ë°ì§ëë¤. ê·¸ëì, (íí ê°ì) ë¶ë³ 컨í ì´ëê° ê°ë³ ê°ì²´ë¡ì 참조를 íê³ ìë¤ë©´, ê·¸ ê°ë³ ê°ì²´ê° ë³ê²½ëë©´ 컨í ì´ëì ê°ë ë³ê²½ë©ëë¤.
Types affect almost all aspects of object behavior. Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.
For example, after a = 1; b = 1, a and b may or may not refer to
the same object with the value one, depending on the implementation.
This is because int is an immutable type, so the reference to 1
can be reused. This behaviour depends on the implementation used, so should
not be relied upon, but is something to be aware of when making use of object
identity tests.
However, after c = []; d = [], c and d are guaranteed to refer to two
different, unique, newly created empty lists. (Note that e = f = [] assigns
the same object to both e and f.)
3.2. íì¤í ê³ì¸µÂ¶
ìëì íì´ì¬ì ë´ì¥ë íë¤ì 목ë¡ì´ ììµëë¤. (구íì ë°ë¼ C ë ìë°ë ë¤ë¥¸ ì¸ì´ë¡ ìì±ë) íì¥ ëª¨ëë¤ì ì¶ê°ì íì ì ìí ì ììµëë¤. íì´ì¬ì 미ë ë²ì ìì í ê³ì¸µì íì ëí ì ìëë° (ì를 ë¤ì´, ì 리ì, í¨ì¨ì ì¼ë¡ ì ì¥ë ì ì ë°°ì´ ë±ë±), íì¤ ë¼ì´ë¸ë¬ë¦¬ë¥¼ íµí´ ì¶ê°ë ê°ë¥ì±ì´ ë í¬ê¸°ë í©ëë¤.
ìëì ëì¤ë ëªëª íì ëí ì¤ëª ì âí¹ì ì´í¸ë¦¬ë·°í¸(special attribute)â 를 ëì´íë 문ë¨ì í¬í¨í©ëë¤. ì´ê²ë¤ì 구íì ì ê·¼í ë°©ë²ì ì ê³µíëë°, ì¼ë°ì ì¸ ì¬ì©ì ìí ê²ì´ ìëëë¤. ì ìë ìì¼ë¡ ë³ê²½ë ì ììµëë¤.
3.2.1. None¶
ì´ íì íëì ê°ë§ì ê°ìµëë¤. ì´ ê°ì ê°ë íëì ê°ì²´ê° ì¡´ì¬í©ëë¤. ì´ ê°ì²´ìë ë´ì¥ë ì´ë¦ None ì íµí´ ì ê·¼í©ëë¤. ì¬ë¬ ê°ì§ ìí©ìì ê°ì ë¶ì¬ë¥¼ ì리ë ë° ì¬ì©ë©ëë¤. ì를 ë¤ì´, ëª
ìì ì¼ë¡ ëê°ë¥¼ ëë ¤ì£¼ì§ ìë í¨ìì ë°í ê°ì
ëë¤. ë
¼ë¦¬ê°ì ê±°ì§ì
ëë¤.
3.2.2. NotImplemented¶
This type has a single value. There is a single object with this value. This
object is accessed through the built-in name NotImplemented. Numeric methods
and rich comparison methods should return this value if they do not implement the
operation for the operands provided. (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.) It
should not be evaluated in a boolean context.
ë ìì¸í ë´ì©ì ì°ì ì°ì° 구í ì ì°¸ê³ íììì¤.
ë²ì 3.9ìì ë³ê²½: Evaluating NotImplemented in a boolean context was deprecated.
ë²ì 3.14ìì ë³ê²½: Evaluating NotImplemented in a boolean context now raises a TypeError.
It previously evaluated to True and emitted a DeprecationWarning
since Python 3.9.
3.2.3. Ellipsis¶
ì´ íì íëì ê°ë§ì ê°ìµëë¤. ì´ ê°ì ê°ë íëì ê°ì²´ê° ì¡´ì¬í©ëë¤. ì´ ê°ì²´ìë 리í°ë´ ... ì´ë ë´ì¥ë ì´ë¦ Ellipsis ì íµí´ ì ê·¼í©ëë¤. ë
¼ë¦¬ê°ì ì°¸ì
ëë¤.
3.2.4. numbers.Number¶
ì´ê²ë¤ì ì«ì 리í°ë´ì ìí´ ë§ë¤ì´ì§ê³ , ì°ì ì°ì°ê³¼ ë´ì¥ ì°ì í¨ìë¤ì´ ê²°ê³¼ë¡ ëë ¤ì¤ëë¤. ì«ì ê°ì²´ë ë¶ë³ì ëë¤; í ë² ê°ì´ ë§ë¤ì´ì§ë©´ ì ë ë³íì§ ììµëë¤. íì´ì¬ì ì«ìë ë¹ì°í ìíì ì¸ ì«ìë¤ê³¼ ë°ì íê² ê´ë ¨ëì´ ììµëë¤, íì§ë§ ì»´í¨í°ì ì«ì ííìì ì ì½ì ë°ê³ ììµëë¤.
The string representations of the numeric classes, computed by
__repr__() and __str__(), have the following
properties:
í´ëì¤ ìì±ìì ì ë¬ë ë ìë ì«ì ê°ì ê°ì§ ê°ì²´ë¥¼ ìì±íë ì í¨í ì«ì 리í°ë´ ì ëë¤.
ê°ë¥íë©´, ííì 10ì§ë²ì ëë¤.
ììì ìì ë¨ì¼ 0ì ì ì¸íê³ , ì í 0ì íìëì§ ììµëë¤.
ììì ë¤ì ë¨ì¼ 0ì ì ì¸íê³ , íí 0ì íìëì§ ììµëë¤.
ë¶í¸ë ì«ìê° ììì¼ ëë§ íìë©ëë¤.
Python distinguishes between integers, floating-point numbers, and complex numbers:
3.2.4.1. numbers.Integral¶
ì´ê²ë¤ì ìíì ì¸ ì ì ì§í©(ìê³¼ ì)ì ìíë ììë¤ì ëíë ëë¤.
ì°¸ê³
ì ì íí ê·ì¹ì ììê° í¬í¨ë ìíí¸ì ë§ì¤í¬ ì°ì°ì ê°ì¥ ì미 ìë í´ìì ì ê³µí기 ìí ê²ì ëë¤.
ë ê°ì§ ì¢ ë¥ì ì ìê° ììµëë¤:
- ì ì (
int) ì´ê²ì (ê°ì) ë©ëª¨ë¦¬ê° íë½íë í, ì ì½ ìë ë²ìì ì«ì를 ííí©ëë¤. ìíí¸(shift)ì ë§ì¤í¬(mask) ì°ì°ì´ 목ì ì¼ ëë ì´ì§ ííì´ ê°ì ëê³ , ììë ì¼ì¢ ì 2ì ë³´ì(2âs complement)ë¡ ííëëë°, ë¶í¸ ë¹í¸ê° ì¼ìª½ì¼ë¡ 무íí íì¥ë ê²ê³¼ ê°ì í¨ê³¼ë¥¼ ì¤ëë¤.
- ë¶ë¦° (
bool) ì´ê²ì ë ¼ë¦¬ê° ê±°ì§ê³¼ ì°¸ì ëíë ëë¤.
FalseìTrueë ê°ì²´ë§ ë¶ë¦° í ê°ì²´ì ëë¤. ë¶ë¦° íì int íì ììí(subtype)ì´ê³ , ëë¶ë¶ ìí©ìì ê°ê¸° 0ê³¼1ì²ë¼ ëìí©ëë¤. ìì¸ë 문ìì´ë¡ ë³íëë ê²½ì°ì¸ë°, ê°ê¸° 문ìì´"False"ì"True"ê° ë°íë©ëë¤.
3.2.4.2. numbers.Real (float)¶
These represent machine-level double precision floating-point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating-point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating-point numbers.
3.2.4.3. numbers.Complex (complex)¶
These represent complex numbers as a pair of machine-level double precision
floating-point numbers. The same caveats apply as for floating-point numbers.
The real and imaginary parts of a complex number z can be retrieved through
the read-only attributes z.real and z.imag.
3.2.5. ìíì¤ë¤Â¶
These represent finite ordered sets indexed by non-negative numbers. The
built-in function len() returns the number of items of a sequence. When
the length of a sequence is n, the index set contains the numbers 0, 1,
â¦, n-1. Item i of sequence a is selected by a[i]. Some sequences,
including built-in sequences, interpret negative subscripts by adding the
sequence length. For example, a[-2] equals a[n-2], the second to last
item of sequence a with length n.
The resulting value must be a nonnegative integer less than the number of items
in the sequence. If it is not, an IndexError is raised.
Sequences also support slicing: a[start:stop] selects all items with index k such
that start <= k < stop. When used as an expression, a slice is a
sequence of the same type. The comment above about negative subscripts also applies
to negative slice positions.
Note that no error is raised if a slice position is less than zero or larger
than the length of the sequence.
If start is missing or None, slicing behaves as if start was zero.
If stop is missing or None, slicing behaves as if stop was equal to
the length of the sequence.
ì´ë¤ ìíì¤ë ì¸ ë²ì§¸ âì¤í
(step)â 매ê°ë³ì를 ì¬ì©íë âíì¥ ì¬ë¼ì´ì±(extended slicing)âë ì§ìí©ëë¤: a[i:j:k] ë x = i + n*k, n >= 0, i <= x < j 를 ë§ì¡±íë 모ë í목 x 를 ì íí©ëë¤.
ìíì¤ë ë¶ë³ì±ì ë°ë¼ 구ë¶ë©ëë¤
3.2.5.1. ë¶ë³ ìíì¤Â¶
ë¶ë³ ìíì¤ íì ê°ì²´ë ì¼ë¨ ë§ë¤ì´ì§ íìë ë³ê²½ë ì ììµëë¤. (ë§ì½ ë¤ë¥¸ ê°ì²´ë¡ì 참조를 í¬í¨íë©´, ê·¸ ê°ì²´ë ê°ë³ì¼ ì ìê³ , ë³ê²½ë ì ììµëë¤; íì§ë§, ë¶ë³ ê°ì²´ë¡ë¶í° 참조ëë ê°ì²´ì ì§í© ìì²´ë ë³ê²½ë ì ììµëë¤.)
ë¤ìê³¼ ê°ì íë¤ì ë¶ë³ ìíì¤ì ëë¤:
- 문ìì´(Strings)
A string (
str) is a sequence of values that represent characters, or more formally, Unicode code points. All the code points in the range0to0x10FFFFcan be represented in a string.Python doesnât have a dedicated character type. Instead, every code point in the string is represented as a string object with length
1.The built-in function
ord()converts a code point from its string form to an integer in the range0to0x10FFFF;chr()converts an integer in the range0to0x10FFFFto the corresponding length1string object.str.encode()can be used to convert astrtobytesusing the given text encoding, andbytes.decode()can be used to achieve the opposite.- íí(Tuples)
The items of a
tupleare arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a âsingletonâ) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.- ë°ì´í¸ì´(Bytes)
A
bytesobject is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256. Bytes literals (likeb'abc') and the built-inbytes()constructor can be used to create bytes objects. Also, bytes objects can be decoded to strings via thedecode()method.
3.2.5.2. ê°ë³ ìíì¤Â¶
ê°ë³ ìíì¤ë ë§ë¤ì´ì§ íì ë³ê²½ë ì ììµëë¤. ìë¸ì¤í¬ë¦½ì
(subscription)ê³¼ ì¬ë¼ì´ì±ì ëì
문과 del (ìì ) 문ì ëìì¼ë¡ ì¬ì©ë ì ììµëë¤.
ì°¸ê³
The collections and array module provide
additional examples of mutable sequence types.
íì¬ ë ê°ì ë´ì¥ ê°ë³ ìíì¤íì´ ììµëë¤:
- 리ì¤í¸(Lists)
리ì¤í¸ì í목ì ììì íì´ì¬ ê°ì²´ì ëë¤. 리ì¤í¸ë 콤ë§ë¡ ë¶ë¦¬ë ííìì ëê´í¸ ìì ë£ì´ì ë§ë¤ ì ììµëë¤. (ê¸¸ì´ 0ì´ë 1ì 리ì¤í¸ë¥¼ ë§ëëë° ë³ëì ê·ì¹ì´ íì ììµëë¤.)
- ë°ì´í¸ ë°°ì´(Byte Arrays)
ë°ì´í¸ ë°°ì´(bytearray) ê°ì²´ë ê°ë³ ë°°ì´ì ëë¤. ë´ì¥
bytearray()ìì±ìë¡ ë§ë¤ì´ì§ëë¤. ê°ë³ì´ë¼ë ê²(ê·¸ëì í´ì± ë¶ê°ë¥íë¤ë ê²)ì ì ì¸íê³ , ë°ì´í¸ ë°°ì´ì ë¶ë³ ë°ì´í¸ì´(bytes) ê°ì²´ì ê°ì ì¸í°íì´ì¤ì 기ë¥ì ì ê³µí©ëë¤.
3.2.6. ì§í© íë¤(Set types)¶
ì´ê²ë¤ì ì¤ë³µ ìë ë¶ë³ ê°ì²´ë¤ì ìì ìê³ ì íí ì§í©ì ëíë
ëë¤. ì¸ë±ì±í ì ììµëë¤. íì§ë§ ì´í°ë ì´í¸í ì ìê³ , ë´ì¥ í¨ì len() ì ì§í© ìì ìë í목ë¤ì ê°ì를 ëë ¤ì¤ëë¤. ì§í©ì ì¼ë°ì ì¸ ì©ëë ë¹ ë¥¸ 멤ë²ì ê²ì¬(fast membership testing), ìíì¤ìì ì¤ë³µë í목 ì ê±°, êµì§í©(intersection), í©ì§í©(union), ì°¨ì§í©(difference), ëì¹ì°¨ì§í©(symmetric difference)ê³¼ ê°ì ì§í© ì°ì°ì ê³ì°íë ê²ì
ëë¤.
ì§í©ì ììë¤ìë ëì
ë리 í¤ì ê°ì ë¶ë³ì± ê·ì¹ì´ ì ì©ë©ëë¤. ì«ì íì ê²½ì°ë ì«ì ë¹êµì ê´í ì¼ë° ìì¹ì´ ì ì©ëë¤ë ì ì 주ìí´ì¼ í©ëë¤: ë§ì½ ë ì«ìê° ê°ë¤ê³ ë¹êµëë©´(ì를 ë¤ì´, 1 ê³¼ 1.0), ê·¸ì¤ íëë§ ì§í©ì ë¤ì´ê° ì ììµëë¤.
íì¬ ë ê°ì ë´ì¥ ì§í© íì´ ììµëë¤:
- ì§í©(Sets)
These represent a mutable set. They are created by the built-in
set()constructor and can be modified afterwards by several methods, such asadd().- ë¶ë³ ì§í©(Frozen sets)
ì´ê²ë¤ì ë¶ë³ ì§í©ì ëíë ëë¤. ë´ì¥
frozenset()ìì±ìë¡ ë§ë¤ ì ììµëë¤. ë¶ë³ ì§í©(frozenset)ì ë¶ë³ì´ê³ í´ì ê°ë¥ íë¯ë¡, ë¤ë¥¸ ì§í©ì ììë, ëì ë리ì í¤ë¡ ì¬ì©ë ì ììµëë¤.
3.2.7. 매í(Mappings)¶
ì´ê²ë¤ì ììì ì¸ë±ì¤ ì§í©ì¼ë¡ ì¸ë±ì±ëë ê°ì²´ë¤ì ì íí ì§í©ì ëíë
ëë¤. ì¸ë±ì¤ í기ë²(subscript notation) a[k] ë 매í a ìì k ë¡ ì¸ë±ì¤ ëë í목ì ì íí©ëë¤; ì´ê²ì ííìì ì¬ì©ë ìë ìê³ , ëì
ì´ë del 문ì¥ì ëìì´ ë ìë ììµëë¤. ë´ì¥ í¨ì len() ì 매íì í¬í¨ë í목ë¤ì ê°ì를 ëë ¤ì¤ëë¤.
íì¬ í ê°ì ë´ì¥ 매í íì´ ììµëë¤:
3.2.7.1. ëì ë리(Dictionaries)¶
ì´ê²ë¤ì ê±°ì ììì ì¸ë±ì¤ ì§í©ì¼ë¡ ì¸ë±ì±ëë ê°ì²´ë¤ì ì íí ì§í©ì ëíë
ëë¤. í¤ë¡ ì¬ì©í ì ìë ê²ë¤ì 리ì¤í¸, ëì
ë리ë ê·¸ ì¸ì ê°ë³í ì¤ìì ìì´ë´í°í°ê° ìëë¼ ê°ì¼ë¡ ë¹êµëë ê²ë¤ë¿ì
ëë¤. ëì
ë리ì í¨ì¨ì ì¸ êµ¬íì´, í¤ì í´ìê°ì´ ëì¤ì ë³ê²½ëì§ ìê³ ê³ì ê°ì ê°ì¼ë¡ ì ì§ëëë¡ ì구íê³ ì기 ë문ì
ëë¤. í¤ë¡ ì¬ì©ëë ì«ì íì ê²½ì°ë ì«ì ë¹êµì ê´í ì¼ë° ìì¹ì´ ì ì©ë©ëë¤: ë§ì½ ë ì«ìê° ê°ë¤ê³ ë¹êµëë©´(ì를 ë¤ì´, 1 ê³¼ 1.0), ë ë¤ ê°ì ëì
ë리 í목ì ì¸ë±ì±íëë° ì¬ì©ë ì ììµëë¤.
ëì ë리ë ì½ì ìì를 ì ì§í©ëë¤, í¤ê° ëì ë리ì ìì°¨ì ì¼ë¡ ì¶ê°ë ììì ê°ì ììë¡ ìì±ë¨ì ë»í©ëë¤. 기존 í¤ë¥¼ êµì²´í´ë ììë ë³ê²½ëì§ ìì§ë§, í¤ë¥¼ ì ê±°íë¤ê° ë¤ì ì½ì íë©´ ì´ì ìì¹ë¥¼ ì ì§íë ëì ëì ì¶ê°ë©ëë¤.
Dictionaries are mutable; they can be created by the {} notation (see
section ëì
ë리 ëì¤íë ì´).
íì¥ ëª¨ë dbm.ndbm ê³¼ dbm.gnu ë ì¶ê°ì 매í íì ì ê³µíëë°, collections 모ë ìì ë§ì°¬ê°ì§ì
ëë¤.
ë²ì 3.7ìì ë³ê²½: ëì ë리ë 3.6 ì´ì ì íì´ì¬ ë²ì ìì ì½ì ìì를 ì ì§íì§ ìììµëë¤. CPython 3.6ìì, ì½ì ììê° ì ì§ëìì§ë§, ê·¸ ìì ìë ì¸ì´ ë³´ì¦ì´ ìëë¼ êµ¬í ì¸ë¶ ì¬íì¼ë¡ ê°ì£¼íììµëë¤.
3.2.8. ì½ë¬ë¸(Callable types)¶
ì´ê²ë¤ì í¨ì í¸ì¶ ì°ì°(í¸ì¶ ì¹ì ì°¸ê³ )ì´ ì ì©ë ì ìë íë¤ì ëë¤:
3.2.8.1. ì¬ì©ì ì ì í¨ì¶
ì¬ì©ì ì ì í¨ì ê°ì²´ë í¨ì ì ì를 íµí´ ë§ë¤ì´ì§ëë¤ (í¨ì ì ì ì¹ì ì°¸ê³ ). í¨ìì íì 매ê°ë³ì(formal parameter) 목ë¡ê³¼ ê°ì ê°ìì í목ì í¬í¨íë ì¸ì(argument) 목ë¡ì¼ë¡ í¸ì¶ëì´ì¼ í©ëë¤.
3.2.8.1.1. Special read-only attributes¶
ì´í¸ë¦¬ë·°í¸ |
ì미 |
|---|---|
|
A reference to the Added in version 3.10. |
|
A reference to the |
|
ì
ê°ì²´ë |
3.2.8.1.2. Special writable attributes¶
Most of these attributes check the type of the assigned value:
ì´í¸ë¦¬ë·°í¸ |
ì미 |
|---|---|
|
The functionâs documentation string, or |
|
The functionâs name.
See also: |
|
The functionâs qualified name.
See also: Added in version 3.3. |
|
í¨ìê° ì ìë 모ëì ì´ë¦ ëë (ìë ê²½ì°) |
|
A |
|
The code object representing the compiled function body. |
|
The namespace supporting arbitrary function attributes.
See also: |
|
A ë²ì 3.14ìì ë³ê²½: Annotations are now lazily evaluated. See PEP 649. |
|
The annotate function for this function, or Added in version 3.14. |
|
A |
|
A Added in version 3.12. |
Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes.
CPython 구í ìì¸: CPythonâs current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future.
Additional information about a functionâs definition can be retrieved from its
code object
(accessible via the __code__ attribute).
3.2.8.2. ì¸ì¤í´ì¤ ë©ìë(Instance methods)¶
ì¸ì¤í´ì¤ ë©ìëë í´ëì¤, í´ëì¤ ì¸ì¤í´ì¤ì 모ë ì½ë¬ë¸ ê°ì²´ (ë³´íµ ì¬ì©ì ì ì í¨ì)ì ê²°í©í©ëë¤.
Special read-only attributes:
|
Refers to the class instance object to which the method is bound |
|
Refers to the original function object |
|
The methodâs documentation
(same as |
|
The name of the method
(same as |
|
The name of the module the method was defined in, or |
Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.
User-defined method objects may be created when getting an attribute of a
class (perhaps via an instance of that class), if that attribute is a
user-defined function object or a
classmethod object.
When an instance method object is created by retrieving a user-defined
function object from a class via one of its
instances, its __self__ attribute is the instance, and the
method object is said to be bound. The new methodâs __func__
attribute is the original function object.
When an instance method object is created by retrieving a classmethod
object from a class or instance, its __self__ attribute is the
class itself, and its __func__ attribute is the function object
underlying the class method.
When an instance method object is called, the underlying function
(__func__) is called, inserting the class instance
(__self__) in front of the argument list. For instance, when
C is a class which contains a definition for a function
f(), and x is an instance of C, calling x.f(1) is
equivalent to calling C.f(x, 1).
When an instance method object is derived from a classmethod object, the
âclass instanceâ stored in __self__ will actually be the class
itself, so that calling either x.f(1) or C.f(1) is equivalent to
calling f(C,1) where f is the underlying function.
It is important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.
3.2.8.3. ì ëë ì´í° í¨ì(Generator functions)¶
A function or method which uses the yield statement (see section
yield 문) is called a generator function. Such a function, when
called, always returns an iterator object which can be used to
execute the body of the function: calling the iteratorâs
iterator.__next__() method will cause the function to execute until
it provides a value using the yield statement. When the
function executes a return statement or falls off the end, a
StopIteration exception is raised and the iterator will have
reached the end of the set of values to be returned.
3.2.8.4. ì½ë£¨í´ í¨ì(Coroutine functions)¶
async def 를 ì¬ì©í´ì ì ìëë í¨ìë ë©ìë를 ì½ë£¨í´ í¨ì (coroutine function) ë¼ê³ ë¶ë¦
ëë¤. ì´ë° í¨ì를 í¸ì¶íë©´ ì½ë£¨í´ ê°ì²´ë¥¼ ëë ¤ì¤ëë¤. await ííìì ë¹ë¡¯í´, async with ì async for 문ì ì¬ì©í ì ììµëë¤. ì½ë£¨í´ ê°ì²´(Coroutine Objects) ì¹ì
ì 참조íììì¤.
3.2.8.5. ë¹ë기 ì ëë ì´í° í¨ì(Asynchronous generator functions)¶
A function or method which is defined using async def and
which uses the yield statement is called a
asynchronous generator function. Such a function, when called,
returns an asynchronous iterator object which can be used in an
async for statement to execute the body of the function.
Calling the asynchronous iteratorâs
aiterator.__anext__ method
will return an awaitable which when awaited
will execute until it provides a value using the yield
expression. When the function executes an empty return
statement or falls off the end, a StopAsyncIteration exception
is raised and the asynchronous iterator will have reached the end of
the set of values to be yielded.
3.2.8.6. ë´ì¥ í¨ì(Built-in functions)¶
A built-in function object is a wrapper around a C function. Examples of
built-in functions are len() and math.sin() (math is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:
__doc__is the functionâs documentation string, orNoneif unavailable. Seefunction.__doc__.__name__is the functionâs name. Seefunction.__name__.__self__is set toNone(but see the next item).__module__is the name of the module the function was defined in orNoneif unavailable. Seefunction.__module__.
3.2.8.7. ë´ì¥ ë©ìë(Built-in methods)¶
This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument. An example of
a built-in method is alist.append(), assuming alist is a list object. In
this case, the special read-only attribute __self__ is set to the object
denoted by alist. (The attribute has the same semantics as it does with
other instance methods.)
3.2.8.8. í´ëì¤(Classes)¶
Classes are callable. These objects normally act as factories for new
instances of themselves, but variations are possible for class types that
override __new__(). The arguments of the call are passed to
__new__() and, in the typical case, to __init__() to
initialize the new instance.
3.2.8.9. í´ëì¤ ì¸ì¤í´ì¤(Class Instances)¶
Instances of arbitrary classes can be made callable by defining a
__call__() method in their class.
3.2.9. 모ë(Modules)¶
Modules are a basic organizational unit of Python code, and are created by
the import system as invoked either by the
import statement, or by calling
functions such as importlib.import_module() and built-in
__import__(). A module object has a namespace implemented by a
dictionary object (this is the dictionary referenced by the
__globals__
attribute of functions defined in the module). Attribute references are
translated to lookups in this dictionary, e.g., m.x is equivalent to
m.__dict__["x"]. A module object does not contain the code object used
to initialize the module (since it isnât needed once the initialization is
done).
ì´í¸ë¦¬ë·°í¸ ëì
ì 모ëì ì´ë¦ ê³µê° ëì
ë리를 ê°±ì í©ëë¤. ì를 ë¤ì´, m.x = 1 ì m.__dict__["x"] = 1 ê³¼ ê°ìµëë¤.
3.2.9.2. Other writable attributes on module objects¶
As well as the import-related attributes listed above, module objects also have the following writable attributes:
- module.__doc__¶
The moduleâs documentation string, or
Noneif unavailable. See also:__doc__ attributes.
- module.__annotations__¶
A dictionary containing variable annotations collected during module body execution. For best practices on working with
__annotations__, seeannotationlib.ë²ì 3.14ìì ë³ê²½: Annotations are now lazily evaluated. See PEP 649.
- module.__annotate__¶
The annotate function for this module, or
Noneif the module has no annotations. See also:__annotate__attributes.Added in version 3.14.
3.2.9.3. Module dictionaries¶
Module objects also have the following special read-only attribute:
- module.__dict__¶
The moduleâs namespace as a dictionary object. Uniquely among the attributes listed here,
__dict__cannot be accessed as a global variable from within a module; it can only be accessed as an attribute on module objects.CPython ì´ ëª¨ë ëì ë리를 ë¹ì°ë ë°©ë² ë문ì, ëì ë리ì ëí ì°¸ì¡°ê° ë¨ììëë¼ë, 모ëì´ ì¤ì½í를 ë²ì´ëë©´ 모ë ëì ë리ë ë¹ìì§ëë¤. ì´ê²ì í¼íë ¤ë©´, ëì ë리를 ë³µì¬íê±°ë ëì ë리를 ì§ì ì´ì©íë ëìì 모ëì ì¡ìëì´ì¼ í©ëë¤.
3.2.10. ì¬ì©ì ì ì í´ëì¤(Custom classes)¶
Custom class types are typically created by class definitions (see section
í´ëì¤ ì ì). A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
C.x is translated to C.__dict__["x"] (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of âdiamondâ inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found at
The Python 2.3 Method Resolution Order.
When a class attribute reference (for class C, say) would yield a
class method object, it is transformed into an instance method object whose
__self__ attribute is C.
When it would yield a staticmethod object,
it is transformed into the object wrapped by the static method
object. See section ëì¤í¬ë¦½í° 구íí기 for another way in which attributes
retrieved from a class may differ from those actually contained in its
__dict__.
í´ëì¤ ì´í¸ë¦¬ë·°í¸ ëì ì í´ëì¤ì ëì ë리를 ê°±ì í ë¿, ì´ë¤ ê²½ì°ë ë¶ëª¨ í´ëì¤ì ëì ë리를 ê±´ë리ì§ë ììµëë¤.
í´ëì¤ ê°ì²´ë í´ëì¤ ì¸ì¤í´ì¤ë¥¼ ëë ¤ì£¼ëë¡(ìë를 ë³´ììì¤) í¸ì¶ë ì ììµëë¤(ì를 ë³´ììì¤).
3.2.10.1. Special attributes¶
ì´í¸ë¦¬ë·°í¸ |
ì미 |
|---|---|
|
The classâs name.
See also: |
|
The classâs qualified name.
See also: |
|
The name of the module in which the class was defined. |
|
A |
|
A |
|
CPython 구í ìì¸: The single base class in the inheritance chain that is responsible
for the memory layout of instances. This attribute corresponds to
|
|
The classâs documentation string, or |
|
A dictionary containing
variable annotations
collected during class body execution. See also:
For best practices on working with ê²½ê³ Accessing the This attribute does not exist on certain builtin classes. On
user-defined classes without ë²ì 3.14ìì ë³ê²½: Annotations are now lazily evaluated. See PEP 649. |
|
The annotate function for this class, or Added in version 3.14. |
|
A Added in version 3.12. |
|
A Added in version 3.13. |
|
The line number of the first line of the class definition,
including decorators.
Setting the Added in version 3.13. |
|
The |
3.2.10.2. Special methods¶
In addition to the special attributes described above, all Python classes also have the following two methods available:
- type.mro()¶
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in
__mro__.
- type.__subclasses__()¶
Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example:
>>> class A: pass >>> class B(A): pass >>> A.__subclasses__() [<class 'B'>]
3.2.11. í´ëì¤ ì¸ì¤í´ì¤(Class instances)¶
A class instance is created by calling a class object (see above). A class
instance has a namespace implemented as a dictionary which is the first place
in which attribute references are searched. When an attribute is not found
there, and the instanceâs class has an attribute by that name, the search
continues with the class attributes. If a class attribute is found that is a
user-defined function object, it is transformed into an instance method
object whose __self__ attribute is the instance. Static method and
class method objects are also transformed; see above under âClassesâ. See
section ëì¤í¬ë¦½í° 구íí기 for another way in which attributes of a class
retrieved via its instances may differ from the objects actually stored in
the classâs __dict__. If no class attribute is found, and the
objectâs class has a __getattr__() method, that is called to satisfy
the lookup.
Attribute assignments and deletions update the instanceâs dictionary, never a
classâs dictionary. If the class has a __setattr__() or
__delattr__() method, this is called instead of updating the instance
dictionary directly.
ì´ë¤ í¹ë³í ì´ë¦ë¤ì ë©ìëë¤ì ê°ì§ë©´, í´ëì¤ ì¸ì¤í´ì¤ë ì«ì, ìíì¤, 매íì¸ ì²í ì ììµëë¤. í¹ì ë©ìë ì´ë¦ë¤ ì¹ì ì ë³´ììì¤.
3.2.11.1. Special attributes¶
- object.__class__¶
The class to which a class instance belongs.
3.2.12. I/O ê°ì²´ (íì¼ ê°ì²´ë¼ê³ ë ìë ¤ì ¸ ììµëë¤)¶
íì¼ ê°ì²´ ë ì´ë¦° íì¼ì ëíë
ëë¤. íì¼ ê°ì²´ë¥¼ ë§ëë ì¬ë¬ ê°ì§ ë¨ì¶ë²ì´ ììµëë¤: open() ë´ì¥ í¨ì, os.popen(), os.fdopen() ê³¼ ìì¼ ê°ì²´ì makefile() ë©ìë (ê·¸ë¦¬ê³ , ìë§ë íì¥ ëª¨ëë¤ì´ ì ê³µíë ë¤ë¥¸ í¨ìë¤ì´ë ë©ìëë¤).
File objects implement common methods, listed below, to simplify usage in generic code. They are expected to be with 문 컨í ì¤í¸ ê´ë¦¬ì.
sys.stdin, sys.stdout, sys.stderr ë ì¸í°í리í°ì íì¤ ì
ë ¥, ì¶ë ¥, ìë¬ ì¤í¸ë¦¼ì¼ë¡ ì´ê¸°íë íì¼ ê°ì²´ë¤ì
ëë¤; 모ë í
ì¤í¸ 모ëë¡ ì´ë ¤ì io.TextIOBase ì¶ì í´ëì¤ì ìí´ ì ìë ì¸í°íì´ì¤ë¥¼ ë°ë¦
ëë¤.
- file.read(size=-1, /)¶
Retrieve up to size data from the file. As a convenience if size is unspecified or -1 retrieve all data available.
- file.write(data, /)¶
Store data to the file.
- file.close()¶
Flush any buffers and close the underlying file.
3.2.13. ë´ë¶ í(Internal types)¶
ì¸í°í리í°ê° ë´ë¶ì ì¼ë¡ ì¬ì©íë ëªëª íë¤ì ì¬ì©ììê² ë ¸ì¶ë©ëë¤. ì¸í°í리í°ì 미ë ë²ì ìì ì´ë¤ì ì ìë ë³ê²½ë ì ìì§ë§, ìì í¨ì ìí´ ì¬ê¸°ì ì¸ê¸í©ëë¤.
3.2.13.1. ì½ë ê°ì²´(Code objects)¶
ì½ë ê°ì²´ë ë°ì´í¸ë¡ ì»´íì¼ë(byte-compiled) ì¤í ê°ë¥í íì´ì¬ ì½ë를 ëíë´ëë°, ê·¸ë¥ ë°ì´í¸ ì½ë ë¼ê³ ë ë¶ë¦ ëë¤. ì½ë ê°ì²´ì í¨ì ê°ì²´ ê°ìë ì°¨ì´ê° ììµëë¤; í¨ì ê°ì²´ë í¨ìì ì ì ê³µê°(globals) (í¨ìê° ì ìë 모ë)ì ëª ìì ì¼ë¡ 참조íê³ ìì§ë§, ì½ë ê°ì²´ë ì´ë¤ 문맥(context)ë ê°ê³ ìì§ ììµëë¤; ëí 기본 ì¸ìê°ë¤ì´ í¨ì ê°ì²´ì ì ì¥ëì´ ìì§ë§ ì½ë ê°ì²´ìë ë¤ì´ìì§ ììµëë¤ (ì¤í ìê°ì ê³ì°ëë ê°ë¤ì ëíë´ê¸° ë문ì ëë¤). í¨ì ê°ì²´ìë ë¬ë¦¬, ì½ë ê°ì²´ë ë¶ë³ì´ê³ ê°ë³ ê°ì²´ë¤ì ëí ì´ë¤ 참조ë (ì§ì í¹ì ê°ì ì ì¼ë¡ë) ê°ê³ ìì§ ììµëë¤.
3.2.13.1.1. Special read-only attributes¶
|
The function name |
|
The fully qualified function name Added in version 3.11. |
|
The total number of positional parameters (including positional-only parameters and parameters with default values) that the function has |
|
The number of positional-only parameters (including arguments with default values) that the function has |
|
The number of keyword-only parameters (including arguments with default values) that the function has |
|
The number of local variables used by the function (including parameters) |
|
A |
|
A |
|
A Note: references to global and builtin names are not included. |
|
A string representing the sequence of bytecode instructions in the function |
|
A |
|
A |
|
The name of the file from which the code was compiled |
|
The line number of the first line of the function |
|
A string encoding the mapping from bytecode offsets to line numbers. For details, see the source code of the interpreter. ë²ì 3.12ë¶í° íì§ë¨: This attribute of code objects is deprecated, and may be removed in Python 3.15. |
|
The required stack size of the code object |
|
An |
The following flag bits are defined for co_flags:
bit 0x04 is set if
the function uses the *arguments syntax to accept an arbitrary number of
positional arguments; bit 0x08 is set if the function uses the
**keywords syntax to accept arbitrary keyword arguments; bit 0x20 is set
if the function is a generator. See ì½ë ê°ì²´ ë¹í¸ íëê·¸ for details
on the semantics of each flags that might be present.
Future feature declarations (for example, from __future__ import division) also use bits
in co_flags to indicate whether a code object was compiled with a
particular feature enabled. See compiler_flag.
Other bits in co_flags are reserved for internal use.
If a code object represents a function and has a docstring,
the CO_HAS_DOCSTRING bit is set in co_flags
and the first item in co_consts is
the docstring of the function.
3.2.13.1.2. Methods on code objects¶
- codeobject.co_positions()¶
Returns an iterable over the source code positions of each bytecode instruction in the code object.
The iterator returns
tuples containing the(start_line, end_line, start_column, end_column). The i-th tuple corresponds to the position of the source code that compiled to the i-th code unit. Column information is 0-indexed utf-8 byte offsets on the given source line.This positional information can be missing. A non-exhaustive lists of cases where this may happen:
Running the interpreter with
-Xno_debug_ranges.Loading a pyc file compiled while using
-Xno_debug_ranges.Position tuples corresponding to artificial instructions.
Line and column numbers that canât be represented due to implementation specific limitations.
When this occurs, some or all of the tuple elements can be
None.Added in version 3.11.
ì°¸ê³
This feature requires storing column positions in code objects which may result in a small increase of disk usage of compiled Python files or interpreter memory usage. To avoid storing the extra information and/or deactivate printing the extra traceback information, the
-Xno_debug_rangescommand line flag or thePYTHONNODEBUGRANGESenvironment variable can be used.
- codeobject.co_lines()¶
Returns an iterator that yields information about successive ranges of bytecodes. Each item yielded is a
(start, end, lineno)tuple:start(anint) represents the offset (inclusive) of the start of the bytecode rangeend(anint) represents the offset (exclusive) of the end of the bytecode rangelinenois anintrepresenting the line number of the bytecode range, orNoneif the bytecodes in the given range have no line number
The items yielded will have the following properties:
The first range yielded will have a
startof 0.The
(start, end)ranges will be non-decreasing and consecutive. That is, for any pair oftuples, thestartof the second will be equal to theendof the first.No range will be backwards:
end >= startfor all triples.The last
tupleyielded will haveendequal to the size of the bytecode.
Zero-width ranges, where
start == end, are allowed. Zero-width ranges are used for lines that are present in the source code, but have been eliminated by the bytecode compiler.Added in version 3.10.
ë 보기
- PEP 626 - Precise line numbers for debugging and other tools.
The PEP that introduced the
co_lines()method.
- codeobject.replace(**kwargs)¶
Return a copy of the code object with new values for the specified fields.
Code objects are also supported by the generic function
copy.replace().Added in version 3.8.
3.2.13.2. íë ì ê°ì²´(Frame objects)¶
Frame objects represent execution frames. They may occur in traceback objects, and are also passed to registered trace functions.
3.2.13.2.1. Special read-only attributes¶
|
Points to the previous stack frame (towards the caller),
or |
|
The code object being executed in this frame.
Accessing this attribute raises an auditing event
|
|
The mapping used by the frame to look up local variables. If the frame refers to an optimized scope, this may return a write-through proxy object. ë²ì 3.13ìì ë³ê²½: Return a proxy for optimized scopes. |
|
The dictionary used by the frame to look up global variables |
|
The dictionary used by the frame to look up built-in (intrinsic) names |
|
The âprecise instructionâ of the frame object (this is an index into the bytecode string of the code object) |
|
The generator or coroutine object that owns this frame,
or Added in version 3.14. |
3.2.13.2.2. Special writable attributes¶
|
If not |
|
Set this attribute to |
|
Set this attribute to |
|
The current line number of the frame â writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to this attribute. |
3.2.13.2.3. Frame object methods¶
íë ì ê°ì²´ë íê°ì§ ë©ìë를 ì§ìí©ëë¤:
- frame.clear()¶
This method clears all references to local variables held by the frame. Also, if the frame belonged to a generator, the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use).
RuntimeErroris raised if the frame is currently executing or suspended.Added in version 3.4.
ë²ì 3.13ìì ë³ê²½: Attempting to clear a suspended frame raises
RuntimeError(as has always been the case for executing frames).
3.2.13.3. í¸ë ì´ì¤ë°± ê°ì²´(Traceback objects)¶
Traceback objects represent the stack trace of an exception.
A traceback object
is implicitly created when an exception occurs, and may also be explicitly
created by calling types.TracebackType.
ë²ì 3.7ìì ë³ê²½: Traceback objects can now be explicitly instantiated from Python code.
For implicitly created tracebacks, when the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback. When an exception handler is
entered, the stack trace is made available to the program. (See section
try 문.) It is accessible as the third item of the
tuple returned by sys.exc_info(), and as the
__traceback__ attribute
of the caught exception.
When the program contains no suitable
handler, the stack trace is written (nicely formatted) to the standard error
stream; if the interpreter is interactive, it is also made available to the user
as sys.last_traceback.
For explicitly created tracebacks, it is up to the creator of the traceback
to determine how the tb_next attributes should be linked to
form a full stack trace.
Special read-only attributes:
|
Points to the execution frame of the current level. Accessing this attribute raises an
auditing event |
|
Gives the line number where the exception occurred |
|
Indicates the âprecise instructionâ. |
The line number and last instruction in the traceback may differ from the
line number of its frame object if the exception
occurred in a
try statement with no matching except clause or with a
finally clause.
- traceback.tb_next¶
The special writable attribute
tb_nextis the next level in the stack trace (towards the frame where the exception occurred), orNoneif there is no next level.ë²ì 3.7ìì ë³ê²½: This attribute is now writable
3.2.13.4. ì¬ë¼ì´ì¤ ê°ì²´(Slice objects)¶
Slice objects are used to represent slices for
__getitem__()
methods. They are also created by the built-in slice() function.
í¹ì ì½ê¸° ì ì© ì´í¸ë¦¬ë·°í¸ë¤: start ë íí(lower bound) ì
ëë¤; stop ì ìí(upper bound) ì
ëë¤; step ì ì¤í
ê°ì
ëë¤; ê° ê°ì ìëµë ê²½ì° None ì
ëë¤. ì´ ì´í¸ë¦¬ë·°í¸ë¤ì ììì íì´ ë ì ììµëë¤.
ì¬ë¼ì´ì¤ ê°ì²´ë íëì ë©ìë를 ì§ìí©ëë¤.
- slice.indices(self, length)¶
ì´ ë©ìëë íëì ì ì ì¸ì length 를 ë°ìì ì¬ë¼ì´ì¤ ê°ì²´ê° ê¸¸ì´ length ì¸ ìíì¤ì ì ì©ëìì ë ê·¸ ì¬ë¼ì´ì¤ì ëí ì 보를 ê³ì°í©ëë¤. ì¸ ê°ì ì ìë¡ êµ¬ì±ë ííì ëë ¤ì¤ëë¤: ì´ê²ë¤ì ê°ê° start ì stop ì¸ë±ì¤ì, step ëë ì¬ë¼ì´ì¤ì ì¤í¸ë¼ì´ë(stride) 길ì´ì ëë¤. ìëµëìê±°ë ë²ì를 ë²ì´ë ì¸ë±ì¤ë¤ì ì¼ë°ì ì¸ ì¬ë¼ì´ì¤ì ê°ì ë°©ë²ì¼ë¡ ë¤ë¤ì§ëë¤.
3.2.13.5. ì¤íí± ë©ìë ê°ì²´(Static method objects)¶
Static method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper
around any other object, usually a user-defined method object. When a static
method object is retrieved from a class or a class instance, the object actually
returned is the wrapped object, which is not subject to any further
transformation. Static method objects are also callable. Static method
objects are created by the built-in staticmethod() constructor.
3.2.13.6. í´ëì¤ ë©ìë ê°ì²´(Class method objects)¶
A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under âinstance methodsâ. Class method objects are created
by the built-in classmethod() constructor.
3.3. í¹ì ë©ìë ì´ë¦ë¤Â¶
A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Pythonâs approach to operator overloading,
allowing classes to define their own behavior with respect to language
operators. For instance, if a class defines a method named
__getitem__(),
and x is an instance of this class, then x[i] is roughly equivalent
to type(x).__getitem__(x, i). Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
AttributeError or TypeError).
Setting a special method to None indicates that the corresponding
operation is not available. For example, if a class sets
__iter__() to None, the class is not iterable, so calling
iter() on its instances will raise a TypeError (without
falling back to __getitem__()). [2]
When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the NodeList interface in the W3Câs Document Object Model.)
3.3.1. 기본ì ì¸ ì»¤ì¤í°ë§ì´ì ì´ì ¶
- object.__new__(cls[, ...])¶
í´ëì¤ cls ì ì ì¸ì¤í´ì¤ë¥¼ ë§ë¤ê¸° ìí´ í¸ì¶ë©ëë¤.
__new__()ë ì¤íí± ë©ìëì ëë¤ (ê·¸ë ê² ì ì¸íì§ ììë ëë í¹ë³í ê²½ì°ì ëë¤)ì¸ë°, 첫 ë²ì§¸ ì¸ìë¡ ë§ë¤ë ¤ê³ íë ì¸ì¤í´ì¤ì í´ëì¤ê° ì ë¬ë©ëë¤. ëë¨¸ì§ ì¸ìë¤ì ê°ì²´ ìì±ì íí(í´ëì¤ í¸ì¶)ì ì ë¬ë ê²ë¤ì ëë¤.__new__()ì ë°í ê°ì ì ê°ì²´ ì¸ì¤í´ì¤ì´ì´ì¼ í©ëë¤ (ë³´íµ cls ì ì¸ì¤í´ì¤).Typical implementations create a new instance of the class by invoking the superclassâs
__new__()method usingsuper().__new__(cls[, ...])with appropriate arguments and then modifying the newly created instance as necessary before returning it.If
__new__()is invoked during object construction and it returns an instance of cls, then the new instanceâs__init__()method will be invoked like__init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to the object constructor.ë§ì½
__new__()ê° cls ì ì¸ì¤í´ì¤ë¥¼ ëë ¤ì£¼ì§ ìì¼ë©´, ì ì¸ì¤í´ì¤ì__init__()ë í¸ì¶ëì§ ììµëë¤.__new__()ë ì£¼ë¡ ë¶ë³í(int, str, tupleê³¼ ê°ì)ì ìë¸ í´ëì¤ê° ì¸ì¤í´ì¤ ìì±ì 커ì¤í°ë§ì´ì¦í ì ìëë¡ íë ë° ì¬ì©ë©ëë¤. ëí, ì¬ì©ì ì ì ë©í í´ëì¤ìì í´ëì¤ ìì±ì 커ì¤í°ë§ì´ì¦í기 ìí´ ì주 ì¬ì©ë©ëë¤.
- object.__init__(self[, ...])¶
(
__new__()ì ìí´) ì¸ì¤í´ì¤ê° ë§ë¤ì´ì§ íì, íì§ë§ í¸ì¶ììê² ëë ¤ì£¼ê¸° ì ì í¸ì¶ë©ëë¤. ì¸ìë¤ì í´ëì¤ ìì±ì ííì¼ë¡ ì ë¬ë ê²ë¤ì ëë¤. ë§ì½ ë² ì´ì¤ í´ëì¤ê°__init__()ë©ìë를 ê°ê³ ìë¤ë©´, ìë¸ í´ëì¤ì__init__()ë©ìëë, ìë¤ë©´, ì¸ì¤í´ì¤ìì ë² ì´ì¤ í´ëì¤ê° ì°¨ì§íë ë¶ë¶ì´ ì¬ë°ë¥´ê² ì´ê¸°íë¨ì íì¤í í기 ìí´ ëª ìì ì¼ë¡ í¸ì¶í´ì£¼ì´ì¼ í©ëë¤; ì를 ë¤ì´:super().__init__([args...]).ê°ì²´ë¥¼ ë§ëëë°
__new__()ì__init__()ê° íë ¥íê³ ìì¼ë¯ë¡ (__new__()ë ë§ë¤ê³ ,__init__()ë ê·¸ê²ì 커ì¤í°ë§ì´ì¦í©ëë¤),__init__()ê°Noneì´ì¸ì ê°ì ëë ¤ì£¼ë©´ ì¤íìê°ìTypeError를 ì¼ì¼íµëë¤.
- object.__del__(self)¶
ì¸ì¤í´ì¤ê° íê´´ë기 ì§ì ì í¸ì¶ë©ëë¤. íì´ëë¼ì´ì ëë (ë¶ì ì íê²) íê´´ìë¼ê³ ë¶ë¦½ëë¤. ë§ì½ ë² ì´ì¤ í´ëì¤ê°
__del__()ë©ìë를 ê°ê³ ìë¤ë©´, ìì í´ëì¤ì__del__()ë©ìëë, ì ìëì´ ìë¤ë©´, ì¸ì¤í´ì¤ìì ë² ì´ì¤ í´ëì¤ê° ì°¨ì§íë ë¶ë¶ì ì ì íê² ìì í기 ìí´, ëª ìì ì¼ë¡ ë² ì´ì¤ í´ëì¤ì ë©ìë를 í¸ì¶í´ì¼ í©ëë¤.(ê¶ì¥íì§ë ìì§ë§!)
__del__()ë©ìëë ì¸ì¤í´ì¤ì ëí ìë¡ì´ 참조를 ë§ë¦ì¼ë¡ì¨ ì¸ì¤í´ì¤ì í괴를 ì§ì°ìí¬ ì ììµëë¤. ì´ê²ì ê°ì²´ ë¶í ì´ë¼ê³ ë¶ë¦ ëë¤. ë¶íí ê°ì²´ê° íê´´ë ë__del__()ì´ ë ë²ì§¸ë¡ í¸ì¶ë ì§ë 구íì ë°ë¼ ë¤ë¦ ëë¤; íì¬ CPython 구íì ì¤ì§ í ë²ë§ í¸ì¶í©ëë¤.It is not guaranteed that
__del__()methods are called for objects that still exist when the interpreter exits.weakref.finalizeprovides a straightforward way to register a cleanup function to be called when an object is garbage collected.ì°¸ê³
del xë ì§ì x.__del__()를 í¸ì¶íì§ ììµëë¤ â ìì ìë ê²ìxì 참조 íì(reference count)를 íë ê°ììí¤ê³ , ë¤ì ìë ê²ìxì 참조 íìê° 0 ì´ ë ë í¸ì¶ë©ëë¤.CPython 구í ìì¸: It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the cyclic garbage collector. A common cause of reference cycles is when an exception has been caught in a local variable. The frameâs locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.
ë 보기
gc모ëì ëí 문ì.ê²½ê³
__del__()ì´ í¸ì¶ëë ë¶ìì í ìí© ë문ì, ì´ê²ì´ ì¤í ì¤ì ë°ììí¤ë ìì¸ë 무ìëê³ , ëì ìsys.stderrë¡ ê²½ê³ ê° ì¶ë ¥ë©ëë¤. í¹í:__del__()ì (ììì ì¤ë ëìì) ììì ì½ëê° ì¤íëë ëì í¸ì¶ë ì ììµëë¤.__del__()ì´ ë¡ì ì»ì´ì¼ íê±°ë ë¤ë¥¸ ë¸ë¡í¹ ììì í¸ì¶íë©´,__del__()ì ì¤íí기 ìí´ ì¤ë¨ë ì½ëê° ììì ì´ë¯¸ ì°¨ì§íì ì ìì¼ë¯ë¡ êµì°© ìíì ë¹ ì§ ì ììµëë¤.__del__()ì ì¸í°í리í°ë¥¼ ì¢ ë£í ë ì¤íë ì ììµëë¤. ê²°ê³¼ì ì¼ë¡, ì¡ì¸ì¤í´ì¼ íë ì ì ë³ì(ë¤ë¥¸ 모ë í¬í¨)ê° ì´ë¯¸ ìì ëìê±°ëNoneì¼ë¡ ì¤ì ëìì ì ììµëë¤. íì´ì¬ì ì´ë¦ì´ íëì ë°ì¤ë¡ ììíë ì ì ê°ì²´ê° ë¤ë¥¸ ì ì ê°ì²´ë¤ë³´ë¤ 먼ì ìì ë¨ì ë³´ì¥í©ëë¤; ì´ê²ì, ë§ì½ ê·¸ ì ì ê°ì²´ë¤ì ëí ë¤ë¥¸ ì°¸ì¡°ê° ì¡´ì¬íì§ ìëë¤ë©´,__del__()ë©ìëê° í¸ì¶ëë ìì ì, ìí¬í¸ë 모ëë¤ì´ ë¨ììëë¡ íì¤í íë ë° ëìì´ ë ì ììµëë¤.
- object.__repr__(self)¶
repr()ë´ì¥ í¨ìì ìí´ í¸ì¶ëì´ ê°ì²´ì âíìì ì¸(official)â 문ìì´ ííì ê³ì°í©ëë¤. ë§ì½ ê°ë¥íë¤ë©´, ì´ê²ì ê°ì (ì ì í íê²½ì´ ì£¼ì´ì§ ë) ê°ì ê°ë ê°ì²´ë¥¼ ìë¡ ë§ë¤ ì ìë ì¬ë°ë¥¸ íì´ì¬ ííìì²ë¼ ë³´ì¬ì¼ í©ëë¤. ê°ë¥íì§ ìë¤ë©´,<...ì¸ëª¨ìë ì¤ëª ...>ííì 문ìì´ì ëë ¤ì¤ì¼ í©ëë¤. ë°í ê°ì ë°ëì 문ìì´ì´ì´ì¼ í©ëë¤. ë§ì½ í´ëì¤ê°__str__()ìì´__repr__()ë§ ì ìíë¤ë©´,__repr__()ì ê·¸ í´ëì¤ ì¸ì¤í´ì¤ì âë¹íìì ì¸(informal)â 문ìì´ ííì´ ì구ë ë ì¬ì©ë ì ììµëë¤.This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. A default implementation is provided by the
objectclass itself.
- object.__str__(self)¶
Called by
str(object), the default__format__()implementation, and the built-in functionprint(), to compute the âinformalâ or nicely printable string representation of an object. The return value must be a str object.ì´ ë©ìëë
__str__()ì´ ì¬ë°ë¥¸ íì´ì¬ ííìì ëë ¤ì¤ ê²ì´ë¼ê³ 기ëëì§ ìëë¤ë ì ììobject.__repr__()ê³¼ ë¤ë¦ ëë¤: ë í¸ë¦¬íê³ ê°ê²°í ííì´ ì¬ì©ë ì ììµëë¤.ë´ì¥í
objectì ì ìë 기본 구íìobject.__repr__()ì í¸ì¶í©ëë¤.
- object.__bytes__(self)¶
Called by bytes to compute a byte-string representation of an object. This should return a
bytesobject. Theobjectclass itself does not provide this method.
- object.__format__(self, format_spec)¶
format()ë´ì¥ í¨ì, íëíë©´, í¬ë§· 문ìì´ ë¦¬í°ë´(formatted string literals) ì ê³ì°ê³¼str.format()ë©ìëì ìí´ í¸ì¶ëì´, ê°ì²´ì âí¬ë§·ëâ 문ìì´ ííì ë§ë¤ì´ë ëë¤. format_spec ì¸ìë ì구ëë í¬ë§· ìµì ë¤ì í¬í¨íë 문ìì´ì ëë¤. format_spec ì¸ìì í´ìì__format__()ì 구ííë íì ë¬ë ¤ìì¼ë, ëë¶ë¶ í´ëì¤ë í¬ë§¤í ì ë´í¥íë¤ì íëë¡ ììíê±°ë, ë¹ì·í í¬ë§· ìµì 문ë²ì ì¬ì©í©ëë¤.íì¤ í¬ë§¤í 문ë²ì ëí´ìë Format specification mini-language 를 ì°¸ê³ íë©´ ë©ëë¤.
ë°í ê°ì ë°ëì 문ìì´ì´ì´ì¼ í©ëë¤.
The default implementation by the
objectclass should be given an empty format_spec string. It delegates to__str__().ë²ì 3.4ìì ë³ê²½:
objectì __format__ ë©ìë ìì ì, ë¹ ë¬¸ìì´ì´ ìë ì¸ìê° ì ë¬ëë©´TypeError를 ë°ììíµëë¤.ë²ì 3.7ìì ë³ê²½: ì´ì
object.__format__(x, '')ëformat(str(x), '')ê° ìëë¼str(x)ì ëë±í©ëë¤.
- object.__lt__(self, other)¶
- object.__le__(self, other)¶
- object.__eq__(self, other)¶
- object.__ne__(self, other)¶
- object.__gt__(self, other)¶
- object.__ge__(self, other)¶
ì´ê²ë¤ì ìì âíë¶í ë¹êµ(rich comparison)â ë©ìëì ëë¤. ì°ì°ì 기í¸ì ë©ìë ì´ë¦ ê°ì ê´ê³ë ë¤ìê³¼ ê°ìµëë¤:
x<yëx.__lt__(y)를 í¸ì¶í©ëë¤,x<=yëx.__le__(y)를 í¸ì¶í©ëë¤,x==yëx.__eq__(y)를 í¸ì¶í©ëë¤,x!=yëx.__ne__(y)를 í¸ì¶í©ëë¤,x>yëx.__gt__(y)를 í¸ì¶í©ëë¤,x>=yëx.__ge__(y)를 í¸ì¶í©ëë¤.A rich comparison method may return the singleton
NotImplementedif it does not implement the operation for a given pair of arguments. By convention,FalseandTrueare returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of anifstatement), Python will callbool()on the value to determine if the result is true or false.By default,
objectimplements__eq__()by usingis, returningNotImplementedin the case of a false comparison:True if x is y else NotImplemented. For__ne__(), by default it delegates to__eq__()and inverts the result unless it isNotImplemented. There are no other implied relationships among the comparison operators or default implementations; for example, the truth of(x<y or x==y)does not implyx<=y. To automatically generate ordering operations from a single root operation, seefunctools.total_ordering().By default, the
objectclass provides implementations consistent with ê° ë¹êµ: equality compares according to object identity, and order comparisons raiseTypeError. Each default method may generate these results directly, but may also returnNotImplemented.ì¬ì©ì ì ì ë¹êµ ì°ì°ì를 ì§ìíê³ ëì ë리 í¤ë¡ ì¬ì©ë ì ìë í´ì ê°ë¥ ê°ì²´ë¥¼ ë§ëë ê²ì ê´í ëª ê°ì§ ì¤ìí ë´ì©ì´
__hash__()ì ê´í 문ë¨ì ëìµëë¤.There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather,
__lt__()and__gt__()are each otherâs reflection,__le__()and__ge__()are each otherâs reflection, and__eq__()and__ne__()are their own reflection. If the operands are of different types, and the right operandâs type is a direct or indirect subclass of the left operandâs type, the reflected method of the right operand has priority, otherwise the left operandâs method has priority. Virtual subclassing is not considered.When no appropriate method returns any value other than
NotImplemented, the==and!=operators will fall back toisandis not, respectively.
- object.__hash__(self)¶
Called by built-in function
hash()and for operations on members of hashed collections includingset,frozenset, anddict. The__hash__()method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example:def __hash__(self): return hash((self.name, self.nick, self.color))
ì°¸ê³
hash()ë ê°ì²´ê° ì ìí__hash__()ë©ìëê° ëë ¤ì£¼ë ê°ìPy_ssize_tì í¬ê¸°ë¡ ìë¦ ëë¤(truncate). ì´ê²ì ë³´íµ 64-bit ë¹ëììë 8ë°ì´í¸ê³ , 32-bit ë¹ëììë 4ë°ì´í¸ì ëë¤. ë§ì½ ê°ì²´ì__hash__()ê° ìë¡ ë¤ë¥¸ ë¹í¸ í¬ê¸°ë¥¼ ê°ë ë¹ëë¤ ì¬ì´ìì í¨ê» ì¬ì©ëì´ì¼ íë¤ë©´, 모ë ì§ìí ë¹ëë¤ììì íì ê²ì¬í´ì¼ í©ëë¤. ì´ë ê² íë ì¬ì´ ë°©ë²ìpython -c "import sys; print(sys.hash_info.width)"ì ëë¤.If a class does not define an
__eq__()method it should not define a__hash__()operation either; if it defines__eq__()but not__hash__(), its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an__eq__()method, it should not implement__hash__(), since the implementation of hashable collections requires that a keyâs hash value is immutable (if the objectâs hash value changes, it will be in the wrong hash bucket).User-defined classes have
__eq__()and__hash__()methods by default (inherited from theobjectclass); with them, all objects compare unequal (except with themselves) andx.__hash__()returns an appropriate value such thatx == yimplies both thatx is yandhash(x) == hash(y).__eq__()를 ì¬ì ìíê³__hash__()를 ì ìíì§ ìë í´ëì¤ë__hash__()ê°Noneì¼ë¡ ì¤ì ë©ëë¤. í´ëì¤ì__hash__()ë©ìëê°Noneì´ë©´, í´ëì¤ì ì¸ì¤í´ì¤ë íë¡ê·¸ë¨ì´ í´ìê°ì ì»ì¼ë ¤ ìëí ëTypeError를 ì¼ì¼í¤ê³ ,isinstance(obj, collections.abc.Hashable)ë¡ ê²ì¬í ë í´ì ê°ë¥íì§ ìë¤ê³ ì¬ë°ë¡ ê°ì§ë©ëë¤.ë§ì½
__eq__()를 ì¬ì ìíë í´ëì¤ê° ë¶ëª¨ í´ëì¤ë¡ë¶í°__hash__()ì 구íì ë¬¼ë ¤ë°ê³ ì¶ì¼ë©´ ì¸í°í리í°ìê² ëª ìì ì¼ë¡ ì´ë ê² ì§ì í´ì£¼ì´ì¼ í©ëë¤:__hash__ = <ParentClass>.__hash__.ë§ì½
__eq__()를 ì¬ì ìíì§ ìë í´ëì¤ê° í´ì ì§ìì ë©ì¶ê³ ì¶ì¼ë©´, í´ëì¤ ì ìì__hash__ = Noneì í¬í¨í´ì¼ í©ëë¤. ìì ì__hash__()ì ì ìí íì ì§ì TypeError를 ì¼ì¼í¤ë ê²½ì°ëisinstance(obj, collections.abc.Hashable)í¸ì¶ì´ í´ì ê°ë¥íë¤ê³ ì못 ì¸ìí©ëë¤.ì°¸ê³
기본ì ì¼ë¡, strê³¼ bytes ê°ì²´ë¤ì
__hash__()ê°ì ì측í ì ìë ëìê°ì¼ë¡ âìí¸ëì´(salted)â ììµëë¤. ê°ë³ íì´ì¬ íë¡ì¸ì¤ ë´ììë ë³íì§ ìë ê°ì¼ë¡ ì ì§ëì§ë§, íì´ì¬ì ë°ë³µì ì¼ë¡ ì¤íí ëë ì측í ì ìê² ë©ëë¤.This is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict insertion, O(n2) complexity. See https://ocert.org/advisories/ocert-2011-003.html for details.
í´ìê°ì ë³ê²½ì ì§í©ì ì´í°ë ì´ì ììì ìí¥ì ì¤ëë¤, íì´ì¬ì ì´ ììì ëí´ ì´ë¤ ë³´ì¥ë íì§ ììµëë¤ (ê·¸ë¦¬ê³ ë³´íµ 32-bit ì 64-bit ë¹ë ì¬ì´ììë ë¤ë¦ ëë¤).
PYTHONHASHSEED를 ì°¸ê³ íììì¤.ë²ì 3.3ìì ë³ê²½: í´ì ëì íë 기본ì ì¼ë¡ íì±íë©ëë¤.
- object.__bool__(self)¶
Called to implement truth value testing and the built-in operation
bool(); should returnFalseorTrue. When this method is not defined,__len__()is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()nor__bool__()(which is true of theobjectclass itself), all its instances are considered true.
3.3.2. ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ 커ì¤í°ë§ì´ì ì´ì ¶
í´ëì¤ ì¸ì¤í´ì¤ì ì´í¸ë¦¬ë·°í¸ 참조(ì½ê¸°, ëì
í기, x.name ì ìì í기)ì ì미를 ë³ê²½í기 ìí´ ë¤ìê³¼ ê°ì ë©ìëë¤ì´ ì ìë ì ììµëë¤.
- object.__getattr__(self, name)¶
Called when the default attribute access fails with an
AttributeError(either__getattribute__()raises anAttributeErrorbecause name is not an instance attribute or an attribute in the class tree forself; or__get__()of a name property raisesAttributeError). This method should either return the (computed) attribute value or raise anAttributeErrorexception. Theobjectclass itself does not provide this method.Note that if the attribute is found through the normal mechanism,
__getattr__()is not called. (This is an intentional asymmetry between__getattr__()and__setattr__().) This is done both for efficiency reasons and because otherwise__getattr__()would have no way to access other attributes of the instance. Note that at least for instance variables, you can take total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()method below for a way to actually get total control over attribute access.
- object.__getattribute__(self, name)¶
í´ëì¤ ì¸ì¤í´ì¤ì ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ë¥¼ 구íí기 ìí´ ì¡°ê±´ ìì´ í¸ì¶ë©ëë¤. ë§ì½ í´ëì¤ê°
__getattr__()ë í¨ê» 구ííë©´,__getattribute__()ê° ëª ìì ì¼ë¡ í¸ì¶íê±°ëAttributeError를 ì¼ì¼í¤ì§ ìë ì´ì __getattr__ ë í¸ì¶ëì§ ììµëë¤. ì´ ë©ìëë ì´í¸ë¦¬ë·°í¸ì (ê³ì°ë) ê°ì ëë ¤ì£¼ê±°ëAttributeErrorìì¸ë¥¼ ì¼ì¼ì¼ì¼ í©ëë¤. ì´ ë©ìëìì 무í ì¬ê·(infinite recursion)ê° ë°ìíë ê²ì ë§ê¸° ìí´, 구íì ì¸ì ë íìí ì´í¸ë¦¬ë·°í¸ì ì ê·¼í기 ìí´ ê°ì ì´ë¦ì ë² ì´ì¤ í´ëì¤ì ë©ìë를 í¸ì¶í´ì¼ í©ëë¤. ì를 ë¤ì´,object.__getattribute__(self, name).ì°¸ê³
This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. See í¹ì ë©ìë ì¡°í.
í¹ì 민ê°í ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ì ê²½ì°, ì¸ì
objìnameì¼ë¡ ê°ì¬ ì´ë²¤í¸object.__getattr__ì ë°ììíµëë¤.
- object.__setattr__(self, name, value)¶
ì´í¸ë¦¬ë·°í¸ ëì ì´ ìëë ë í¸ì¶ë©ëë¤. ì¼ë°ì ì¸ ë©ì»¤ëì¦(ì¦ ì¸ì¤í´ì¤ ëì ë리ì ê°ì ì ì¥íë ê²) ëì ì ì´ê²ì´ í¸ì¶ë©ëë¤. name ì ì´í¸ë¦¬ë·°í¸ ì´ë¦ì´ê³ , value ë ê·¸ê²ì ëì íë ¤ë ê°ì ëë¤.
__setattr__()ìì ì¸ì¤í´ì¤ ì´í¸ë¦¬ë·°í¸ì ëì íë ¤ê³ í ëë, ê°ì ì´ë¦ì ë² ì´ì¤ í´ëì¤ì ë©ìë를 í¸ì¶í´ì¼ í©ëë¤. ì를 ë¤ì´object.__setattr__(self, name, value)í¹ì 민ê°í ì´í¸ë¦¬ë·°í¸ ëì ì ê²½ì°, ì¸ì
obj,name,valueë¡ ê°ì¬ ì´ë²¤í¸object.__setattr__ì ë°ììíµëë¤.
- object.__delattr__(self, name)¶
__setattr__()ê³¼ ë¹ì·íì§ë§ ì´í¸ë¦¬ë·°í¸ë¥¼ ëì íë ëì ì ìì í©ëë¤. ì´ê²ìdel obj.nameì´ ê°ì²´ì ìë¯¸ê° ìë ê²½ì°ìë§ êµ¬íëì´ì¼ í©ëë¤.í¹ì 민ê°í ì´í¸ë¦¬ë·°í¸ ìì ì ê²½ì°, ì¸ì
objìnameì¼ë¡ ê°ì¬ ì´ë²¤í¸object.__delattr__ì ë°ììíµëë¤.
- object.__dir__(self)¶
Called when
dir()is called on the object. An iterable must be returned.dir()converts the returned iterable to a list and sorts it.
3.3.2.1. 모ë ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ 커ì¤í°ë§ì´ì ì´ì ¶
í¹ìí ì´ë¦ __getattr__ ê³¼ __dir__ ë 모ë ì´í¸ë¦¬ë·°í¸ì ëí ì ê·¼ì ì¬ì©ì ì ìíë ë° ì¬ì©ë ìë ììµëë¤. 모ë ìì¤ì __getattr__ í¨ìë íëì ì¸ìë¡ ì´í¸ë¦¬ë·°í¸ì ì´ë¦ì ë°ìì ê³ì°ë ê°ì ëë ¤ì£¼ê±°ë AttributeError 를 ë°ììì¼ì¼ í©ëë¤. ì¼ë°ì ì¸ ì¡°í(ì¦ object.__getattribute__())를 íµí´ ì´í¸ë¦¬ë·°í¸ê° 모ë ê°ì²´ìì ë°ê²¬ëì§ ìì¼ë©´, AttributeError 를 ì¼ì¼í¤ê¸° ì ì 모ë __dict__ ìì __getattr__ ì ê²ìí©ëë¤. ë°ê²¬ëë©´, ì´í¸ë¦¬ë·°í¸ ì´ë¦ì¼ë¡ ê·¸ í¨ì를 í¸ì¶íê³ ê²°ê³¼ë¥¼ ëë ¤ì¤ëë¤.
The __dir__ function should accept no arguments, and return an iterable of
strings that represents the names accessible on module. If present, this
function overrides the standard dir() search on a module.
- module.__class__¶
모ë ëì(ì´í¸ë¦¬ë·°í¸ ì¤ì , íë¡í¼í° ë±)ì ë³´ë¤ ì¸ë°íê² ì¬ì©ì ì ìíë ¤ë©´, 모ë ê°ì²´ì __class__ ì´í¸ë¦¬ë·°í¸ë¥¼ types.ModuleType ì ìë¸ í´ëì¤ë¡ ì¤ì í ì ììµëë¤. ì를 ë¤ë©´:
import sys
from types import ModuleType
class VerboseModule(ModuleType):
def __repr__(self):
return f'Verbose {self.__name__}'
def __setattr__(self, attr, value):
print(f'Setting {attr}...')
super().__setattr__(attr, value)
sys.modules[__name__].__class__ = VerboseModule
ì°¸ê³
모ë __getattr__ ì ìì 모ë __class__ ì¤ì ì ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ 구문ì ì¬ì©íë ì¡°íìë§ ìí¥ì 미칩ëë¤ â 모ë ì ìì ëí ì§ì ì ì¸ ì¡ì¸ì¤(모ë ë´ì ì½ëì ìí ì¡ì¸ì¤ì´ê±°ë 모ëì ì ì ëì
ë리ì ëí 참조를 ê±°ì¹ê±°ë)ë ìí¥ë°ì§ ììµëë¤.
ë²ì 3.5ìì ë³ê²½: ì´ì __class__ 모ë ì´í¸ë¦¬ë·°í¸ê° ì°ê¸° ê°ë¥í©ëë¤.
Added in version 3.7: __getattr__ ê³¼ __dir__ 모ë ì´í¸ë¦¬ë·°í¸.
ë 보기
- PEP 562 - 모ë __getattr__ ê³¼ __dir__
모ëì ëí
__getattr__ê³¼__dir__í¨ì를 ì¤ëª í©ëë¤.
3.3.2.2. ëì¤í¬ë¦½í° 구íí기¶
The following methods only apply when an instance of the class containing the
method (a so-called descriptor class) appears in an owner class (the
descriptor must be in either the ownerâs class dictionary or in the class
dictionary for one of its parents). In the examples below, âthe attributeâ
refers to the attribute whose name is the key of the property in the owner
classâ __dict__. The object class itself does not
implement any of these protocols.
- object.__get__(self, instance, owner=None)¶
ìì ì í´ëì¤(í´ëì¤ ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤) ë ê·¸ í´ëì¤ì ì¸ì¤í´ì¤(ì¸ì¤í´ì¤ ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤)ì ì´í¸ë¦¬ë·°í¸ë¥¼ ì·¨íë ¤ê³ í ë í¸ì¶ë©ëë¤. ì íì owner ì¸ìë ìì ì í´ëì¤ì ëë¤. ë°ë©´ì instance ë ì´í¸ë¦¬ë·°í¸ ì°¸ì¡°ê° ì¼ì´ëê³ ìë ì¸ì¤í´ì¤ì´ê±°ë, ì´í¸ë¦¬ë·°í¸ê° owner 를 íµí´ ì¡ì¸ì¤ ëë ê²½ì° None ì ëë¤.
ì´ ë©ìëë ê³ì°ë ì´í¸ë¦¬ë·°í¸ ê°ì ëë ¤ì£¼ê±°ë
AttributeErrorìì¸ë¥¼ ì¼ì¼ì¼ì¼ í©ëë¤.PEP 252ë
__get__()ì´ íëë ë ê°ì ì¸ì를 ê°ë ì½ë¬ë¸ì´ë¼ê³ ì§ì í©ëë¤. íì´ì¬ ìì ì ë´ì¥ ëì¤í¬ë¦½í°ë ì´ ëª ì¸ë¥¼ ì§ìí©ëë¤; ê·¸ë¬ë, ì¼ë¶ ì ì¼ì ë구ìë ë ì¸ì를 모ë ì구íë ëì¤í¬ë¦½í°ê° ìì ì ììµëë¤. íì´ì¬ ìì ì__getattribute__()구íì íìíì§ì ê´ê³ìì´ íì ë ì¸ì를 모ë ì ë¬í©ëë¤.
- object.__set__(self, instance, value)¶
ìì ì í´ëì¤ì ì¸ì¤í´ì¤ instance ì ì´í¸ë¦¬ë·°í¸ë¥¼ ì ê° value ë¡ ì¤ì í ë í¸ì¶ë©ëë¤.
__set__()ì´ë__delete__()를 ì¶ê°íë©´ ëì¤í¬ë¦½í° ì íì´ âë°ì´í° ëì¤í¬ë¦½í°(data descriptor)âë¡ ë³ê²½ë¨ì ì ìíììì¤. ìì¸í ë´ì©ì ëì¤í¬ë¦½í° í¸ì¶í기를 참조íììì¤.
- object.__delete__(self, instance)¶
ìì ì í´ëì¤ì ì¸ì¤í´ì¤ instance ì ì´í¸ë¦¬ë·°í¸ë¥¼ ìì í ë í¸ì¶ë©ëë¤.
Instances of descriptors may also have the __objclass__ attribute
present:
- object.__objclass__¶
The attribute
__objclass__is interpreted by theinspectmodule as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).
3.3.2.3. ëì¤í¬ë¦½í° í¸ì¶í기¶
In general, a descriptor is an object attribute with âbinding behaviorâ, one
whose attribute access has been overridden by methods in the descriptor
protocol: __get__(), __set__(), and
__delete__(). If any of
those methods are defined for an object, it is said to be a descriptor.
ì´í¸ë¦¬ë·°í¸ ì¡ì¸ì¤ì 기본 ëìì ê°ì²´ì ëì
ë리ìì ì´í¸ë¦¬ë·°í¸ë¥¼ ì½ê³ , ì°ê³ , ìì íë ê²ì
ëë¤. ì를 ë¤ì´ a.x ë a.__dict__['x'] ìì ììí´ì type(a).__dict__['x'] 를 ê±°ì³ type(a) ì ë©í í´ëì¤ë¥¼ ì ì¸í ë² ì´ì¤ í´ëì¤ë¤ì ê±°ì³ ê°ë ì¼ë ¨ì ì¡°íë¡ êµ¬ì±ë©ëë¤.
ê·¸ë¬ë, ë§ì½ ì¡°íí ê°ì´ ëì¤í¬ë¦½í° ë©ìë를 구íí ê°ì²´ë©´, íì´ì¬ì 기본 ëì ëì ì ëì¤í¬ë¦½í° ë©ìë를 í¸ì¶í ì ììµëë¤. ì°ì ìì 목ë¡ì ì´ë ìì¹ìì ì´ë° ì¼ì´ ì¼ì´ëëì§ë ì´ë¤ ëì¤í¬ë¦½í° ë©ìëê° ì ìëì´ ìê³ ì´ë¤ ìì¼ë¡ í¸ì¶ëëì§ì ë°ë¼ ë¤ë¦ ëë¤.
ëì¤í¬ë¦½í° í¸ì¶ì ììì ì ê²°í©(binding)ì
ëë¤, a.x. ì´ë»ê² ì¸ìë¤ì´ ì¡°í©ëëì§ë a ì ë°ë¼ ë¤ë¦
ëë¤:
- ì§ì í¸ì¶
ê°ì¥ ê°ë¨íë©´ìë ê°ì¥ ë ì¬ì©ëë í¸ì¶ì ì¬ì©ìì ì½ëê° ëì¤í¬ë¦½í° ë©ìë를 ì§ì í¸ì¶í ëì ëë¤:
x.__get__(a)- ì¸ì¤í´ì¤ ê²°í©
ê°ì²´ ì¸ì¤í´ì¤ì ê²°í©íë©´,
a.xë ì´ë° í¸ì¶ë¡ ë³íë©ëë¤:type(a).__dict__['x'].__get__(a, type(a)).- í´ëì¤ ê²°í©
í´ëì¤ì ê²°í©íë©´,
A.xë ì´ë° í¸ì¶ë¡ ë³íë©ëë¤:A.__dict__['x'].__get__(None, A).- Super ê²°í©
A dotted lookup such as
super(A, a).xsearchesa.__class__.__mro__for a base classBfollowingAand then returnsB.__dict__['x'].__get__(a, A). If not a descriptor,xis returned unchanged.
For instance bindings, the precedence of descriptor invocation depends on
which descriptor methods are defined. A descriptor can define any combination
of __get__(), __set__() and
__delete__(). If it does not
define __get__(), then accessing the attribute will return the descriptor
object itself unless there is a value in the objectâs instance dictionary. If
the descriptor defines __set__() and/or __delete__(), it is a data
descriptor; if it defines neither, it is a non-data descriptor. Normally, data
descriptors define both __get__() and __set__(), while non-data
descriptors have just the __get__() method. Data descriptors with
__get__() and __set__() (and/or __delete__()) defined
always override a redefinition in an
instance dictionary. In contrast, non-data descriptors can be overridden by
instances.
Python methods (including those decorated with
@staticmethod and @classmethod) are
implemented as non-data descriptors. Accordingly, instances can redefine and
override methods. This allows individual instances to acquire behaviors that
differ from other instances of the same class.
property() í¨ìë ë°ì´í° ëì¤í¬ë¦½í°ë¡ 구íë©ëë¤. ì´ ë문ì, ì¸ì¤í´ì¤ë íë¡í¼í°(property)ì ëìì ë³ê²½í ì ììµëë¤.
3.3.2.4. __slots__¶
__slots__ allow us to explicitly declare data members (like
properties) and deny the creation of __dict__ and __weakref__
(unless explicitly declared in __slots__ or available in a parent.)
The space saved over using __dict__ can be significant.
Attribute lookup speed can be significantly improved as well.
- object.__slots__¶
This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of
__dict__and __weakref__ for each instance.
Notes on using __slots__:
When inheriting from a class without __slots__, the
__dict__and __weakref__ attribute of the instances will always be accessible.Without a
__dict__variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raisesAttributeError. If dynamic assignment of new variables is desired, then add'__dict__'to the sequence of strings in the __slots__ declaration.Without a __weakref__ variable for each instance, classes defining __slots__ do not support
weak referencesto its instances. If weak reference support is needed, then add'__weakref__'to the sequence of strings in the __slots__ declaration.__slots__ are implemented at the class level by creating descriptors for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment.
The action of a __slots__ declaration is not limited to the class where it is defined. __slots__ declared in parents are available in child classes. However, instances of a child subclass will get a
__dict__and __weakref__ unless the subclass also defines __slots__ (which should only contain names of any additional slots).í´ëì¤ê° ë² ì´ì¤ í´ëì¤ì __slots__ ì ì ìë ì´ë¦ê³¼ ê°ì ì´ë¦ì ë³ì를 __slots__ ì ì ì¸íë¤ë©´, ë² ì´ì¤ í´ëì¤ê° ì ìí ë³ìë ì¡ì¸ì¤í ì ìë ìíê° ë©ëë¤(ë² ì´ì¤ í´ëì¤ë¡ë¶í° ëì¤í¬ë¦½í°ë¥¼ ì§ì ì¡°ííë ê²½ì°ë ìì¸ë¤). ì´ê²ì íë¡ê·¸ë¨ì ì ìëì§ ìì ìíë¡ ë³´ë´ê² ë©ëë¤. 미ëìë, ì´ë¥¼ ë°©ì§í기 ìí ê²ì¬ê° ì¶ê°ë ê²ì ëë¤.
TypeErrorwill be raised if nonempty __slots__ are defined for a class derived from a"variable-length" built-in typesuch asint,bytes, andtuple.Any non-string iterable may be assigned to __slots__.
If a
dictionaryis used to assign __slots__, the dictionary keys will be used as the slot names. The values of the dictionary can be used to provide per-attribute docstrings that will be recognised byinspect.getdoc()and displayed in the output ofhelp().__class__assignment works only if both classes have the same __slots__.Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise
TypeError.If an iterator is used for __slots__ then a descriptor is created for each of the iteratorâs values. However, the __slots__ attribute will be an empty iterator.
3.3.3. í´ëì¤ ìì± ì»¤ì¤í°ë§ì´ì ì´ì ¶
Whenever a class inherits from another class, __init_subclass__() is
called on the parent class. This way, it is possible to write classes which
change the behavior of subclasses. This is closely related to class
decorators, but where class decorators only affect the specific class theyâre
applied to, __init_subclass__ solely applies to future subclasses of the
class defining the method.
- classmethod object.__init_subclass__(cls)¶
ì´ ë©ìëë í¬í¨íë í´ëì¤ì ìë¸ í´ëì¤ê° ë§ë¤ì´ì§ ëë§ë¤ í¸ì¶ë©ëë¤. cls ë ì ìë¸ í´ëì¤ì ëë¤. ë§ì½ ì¼ë°ì ì¸ ì¸ì¤í´ì¤ ë©ìëë¡ ì ìëë©´, ì´ ë©ìëë 묵ìì ì¼ë¡ í´ëì¤ ë©ìëë¡ ë³ê²½ë©ëë¤.
Keyword arguments which are given to a new class are passed to the parent classâs
__init_subclass__. For compatibility with other classes using__init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class, as in:class Philosopher: def __init_subclass__(cls, /, default_name, **kwargs): super().__init_subclass__(**kwargs) cls.default_name = default_name class AustralianPhilosopher(Philosopher, default_name="Bruce"): pass
기본 구í
object.__init_subclass__ë ì무 ì¼ë íì§ ìì§ë§, ì¸ìê° í¬í¨ëì´ í¸ì¶ëë©´ ìì¸ë¥¼ ë°ììíµëë¤.ì°¸ê³
ë©í í´ëì¤ íí¸
metaclassë ëë¨¸ì§ í ì ì°¨ì ìí´ ìë¹ëê³ ,__init_subclass__ë¡ ì ë¬ëì§ ììµëë¤. ì¤ì ë©í í´ëì¤ (ëª ìì ì¸ íí¸ ëì ì) ëtype(cls)ë¡ ì¡ì¸ì¤í ì ììµëë¤.Added in version 3.6.
When a class is created, type.__new__() scans the class variables
and makes callbacks to those with a __set_name__() hook.
- object.__set_name__(self, owner, name)¶
Automatically called at the time the owning class owner is created. The object has been assigned to name in that class:
class A: x = C() # Automatically calls: x.__set_name__(A, 'x')
If the class variable is assigned after the class is created,
__set_name__()will not be called automatically. If needed,__set_name__()can be called directly:class A: pass c = C() A.x = c # The hook is not called c.__set_name__(A, 'x') # Manually invoke the hook
ë ìì¸í ë´ì©ì í´ëì¤ ê°ì²´ ë§ë¤ê¸° ì ì°¸ê³ íììì¤.
Added in version 3.6.
3.3.3.1. ë©í í´ëì¤Â¶
기본ì ì¼ë¡, í´ëì¤ë type() ì ì¬ì©í´ì ë§ë¤ì´ì§ëë¤. í´ëì¤ì ë°ëë ì ì´ë¦ ê³µê°ìì ì¤íëê³ , í´ëì¤ ì´ë¦ì type(name, bases, namespace) ì ê²°ê³¼ì ì§ìì ì¼ë¡ ì°ê²°ë©ëë¤.
í´ëì¤ë¥¼ ë§ëë ê³¼ì ì í´ëì¤ ì ì ì¤ì metaclass í¤ìë ì¸ì를 ì ë¬íê±°ë, ê·¸ë° ì¸ì를 í¬í¨í ì´ë¯¸ ì¡´ì¬íë í´ëì¤ë¥¼ ê³ì¹í¨ì¼ë¡ì¨ 커ì¤í°ë§ì´ì¦ë ì ììµëë¤. ë¤ì ììì, MyClass ì MySubclass ë 모ë Meta ì ì¸ì¤í´ì¤ì
ëë¤.
class Meta(type):
pass
class MyClass(metaclass=Meta):
pass
class MySubclass(MyClass):
pass
í´ëì¤ ì ììì ì§ì ë ë¤ë¥¸ í¤ìë ì¸ìë¤ì ìëìì ì¤ëª ëë 모ë ë©í í´ëì¤ ì°ì°ë¤ë¡ ì ë¬ë©ëë¤.
í´ëì¤ ì ìê° ì¤íë ë, ë¤ìê³¼ ê°ì ë¨ê³ê° ìíë©ëë¤.:
MRO íëª©ì´ ê²°ì ë©ëë¤;
ì ì í ë©í í´ëì¤ê° ê²°ì ë©ëë¤;
í´ëì¤ ì´ë¦ ê³µê°ì´ ì¤ë¹ë©ëë¤;
í´ëì¤ ë°ëê° ì¤íë©ëë¤;
í´ëì¤ ê°ì²´ê° ë§ë¤ì´ì§ëë¤.
3.3.3.2. MRO í목 ê²°ì í기¶
- object.__mro_entries__(self, bases)¶
If a base that appears in a class definition is not an instance of
type, then an__mro_entries__()method is searched on the base. If an__mro_entries__()method is found, the base is substituted with the result of a call to__mro_entries__()when creating the class. The method is called with the original bases tuple passed to the bases parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.
ë 보기
types.resolve_bases()Dynamically resolve bases that are not instances of
type.types.get_original_bases()Retrieve a classâs âoriginal basesâ prior to modifications by
__mro_entries__().- PEP 560
Core support for typing module and generic types.
3.3.3.3. ì ì í ë©í í´ëì¤ ì íí기¶
í´ëì¤ ì ìì ì ì í ë©í í´ëì¤ë ë¤ìê³¼ ê°ì´ ê²°ì ë©ëë¤:
ë² ì´ì¤ì ëª ìì ì¸ ë©í í´ëì¤ë¥¼ ì£¼ì§ ìë ê²½ì°
type()ì´ ì¬ì©ë©ëë¤;ëª ìì ì¸ ë©í í´ëì¤ê° ì§ì ëê³ , ê·¸ê²ì´
type()ì ì¸ì¤í´ì¤ê° ìëë©´, ê·¸ê²ì ë©í í´ëì¤ë¡ ì¬ì©í©ëë¤;type()ì ì¸ì¤í´ì¤ê° ëª ìì ì¸ ë©í í´ëì¤ë¡ 주ì´ì§ê±°ë, ë² ì´ì¤ê° ì ìëìì¼ë©´, ê°ì¥ ë§ì´ íìë ë©í í´ëì¤ê° ì¬ì©ë©ëë¤.
ê°ì¥ ë§ì´ íìë ë©í í´ëì¤ë ëª
ìì ì¼ë¡ ì§ì ë ë©í í´ëì¤(ìë¤ë©´)ì ì§ì ë 모ë ë² ì´ì¤ í´ëì¤ë¤ì ë©í í´ëì¤ë¤(ì¦, type(cls)) ì¤ìì ì íë©ëë¤. ê°ì¥ ë§ì´ íìë ë©í í´ëì¤ë ì´ë¤ 모ë ì ìë¸ íì
(subtype)ì
ëë¤. ë§ì½ ì´ë ê²ë ì´ ì¡°ê±´ì ë§ì¡±íì§ ëª»íë¤ë©´, í´ëì¤ ì ìë TypeError 를 ë°ììí¤ë©° ì¤í¨í©ëë¤.
3.3.3.4. í´ëì¤ ì´ë¦ ê³µê° ì¤ë¹í기¶
Once the appropriate metaclass has been identified, then the class namespace
is prepared. If the metaclass has a __prepare__ attribute, it is called
as namespace = metaclass.__prepare__(name, bases, **kwds) (where the
additional keyword arguments, if any, come from the class definition). The
__prepare__ method should be implemented as a
classmethod. The
namespace returned by __prepare__ is passed in to __new__, but when
the final class object is created the namespace is copied into a new dict.
ë§ì½ ë©í í´ëì¤ì __prepare__ ì´í¸ë¦¬ë·°í¸ê° ìë¤ë©´, í´ëì¤ ì´ë¦ ê³µê°ì ë¹ ìì ìë 매íì¼ë¡ ì´ê¸°íë©ëë¤.
ë 보기
- PEP 3115 - íì´ì¬ 3000 ììì ë©í í´ëì¤
__prepare__ì´ë¦ ê³µê° í ì ëì íìµëë¤
3.3.3.5. í´ëì¤ ë°ë ì¤íí기¶
í´ëì¤ ë°ëë (ëëµ) exec(body, globals(), namespace) ê³¼ê°ì´ ì¤íë©ëë¤. ì¼ë°ì ì¸ exec() í¸ì¶ê³¼ 주ë ì°¨ì´ì ì í´ëì¤ ì ìê° í¨ì ë´ë¶ìì ì´ë£¨ì´ì§ ë ì´í ì¤ì½í(lexical scoping) ì´ í´ëì¤ ë°ë(모ë ë©ìëë¤ì í¬í¨í´ì)ë¡ íì¬ê¸ íì¬ì ì¸ë¶ ì¤ì½íì ìë ì´ë¦ë¤ì 참조íëë¡ íë½íë¤ë ê²ì
ëë¤.
íì§ë§, í´ëì¤ ì ìê° í¨ì ë´ë¶ìì ì´ë£¨ì´ì§ ëì¡°ì°¨ë, í´ëì¤ ë´ë¶ìì ì ìë ë©ìëë¤ì í´ëì¤ ì¤ì½íìì ì ìë ì´ë¦ë¤ì ë³¼ ì ììµëë¤. í´ëì¤ ë³ìë ì¸ì¤í´ì¤ë í´ëì¤ ë©ìëì 첫 ë²ì§¸ 매ê°ë³ì를 íµí´ ì¡ì¸ì¤íê±°ë ë¤ì ì¹ì
ìì ì¤ëª
íë 묵ìì ì¼ë¡ ì´í ì¤ì½íë __class__ 참조를 íµí´ì¼ í©ëë¤.
3.3.3.6. í´ëì¤ ê°ì²´ ë§ë¤ê¸°Â¶
ì¼ë¨ í´ëì¤ ì´ë¦ ê³µê°ì´ í´ëì¤ ë°ë를 ì¤íí¨ì¼ë¡ì¨ ì±ìì§ë©´, í´ëì¤ ê°ì²´ê° metaclass(name, bases, namespace, **kwds) ì íµí´ ë§ë¤ì´ì§ëë¤(ì¬ê¸°ìì ì ë¬ëë ì¶ê°ì ì¸ í¤ìë ì¸ìë¤ì __prepare__ ì ì ë¬ë ê²ë¤ê³¼ ê°ìµëë¤).
ì´ í´ëì¤ ê°ì²´ë super() ì ì¸ì를 ì£¼ì§ ìë ê²½ì° ì°¸ì¡°ëë ê²ì
ëë¤. __class__ ë í´ëì¤ ë°ëì ë©ìëë¤ ì¤ ì´ë íëë¼ë __class__ ë super 를 참조í ê²½ì° ì»´íì¼ë¬ì ìí´ ë§ë¤ì´ì§ë 묵ìì ì¸ í´ë¡ì (closure) 참조ì
ëë¤. ì´ê²ì ì¸ì ìë ííì super() ê° ì´í ì¤ì½í 기ë°ì¼ë¡ íì¬ ì ìëê³ ìë í´ëì¤ë¥¼ ì¬ë°ë¥´ê² ì°¾ì ì ìëë¡ í©ëë¤. ë°ë©´ì íì¬ì í¸ì¶ì ì¬ì©ë í´ëì¤ë ì¸ì¤í´ì¤ë ë©ìëë¡ ì ë¬ë 첫 ë²ì§¸ ì¸ìì 기ì´í´ì ìë³ë©ëë¤.
CPython 3.6 ì´ììì, __class__ ì
(cell)ì í´ëì¤ ì´ë¦ ê³µê°ì __classcell__ ìí¸ë¦¬ë¡ ë©í í´ëì¤ì ì ë¬ë©ëë¤. ë§ì½ ì¡´ì¬íë¤ë©´, ì´ê²ì í´ëì¤ê° ì¬ë°ë¥´ê² ì´ê¸°íë기 ìí´ type.__new__ í¸ì¶ê¹ì§ ê±°ì¬ë¬ì ì íëì´ì¼ í©ëë¤. ì´ë ê² íì§ ëª»íë©´ íì´ì¬ 3.8 ììë RuntimeErrorë¡ ì´ì´ì§ ê²ì
ëë¤.
When using the default metaclass type, or any metaclass that ultimately
calls type.__new__, the following additional customization steps are
invoked after creating the class object:
The
type.__new__method collects all of the attributes in the class namespace that define a__set_name__()method;Those
__set_name__methods are called with the class being defined and the assigned name of that particular attribute;The
__init_subclass__()hook is called on the immediate parent of the new class in its method resolution order.
í´ëì¤ ê°ì²´ê° ë§ë¤ì´ì§ íì, í´ëì¤ ì ìì í¬í¨ë í´ëì¤ ë°ì½ë ì´í°ë¤ìê² (ìë¤ë©´) í´ëì¤ë¥¼ ì ë¬íê³ , ê·¸ 결과를 í´ëì¤ê° ì ìëë ì§ì ì´ë¦ ê³µê°ì ì°ê²°í©ëë¤.
When a new class is created by type.__new__, the object provided as the
namespace parameter is copied to a new ordered mapping and the original
object is discarded. The new copy is wrapped in a read-only proxy, which
becomes the __dict__ attribute of the class object.
ë 보기
- PEP 3135 - ì super
묵ìì ì¸ __class__ í´ë¡ì 참조를 ì¤ëª í©ëë¤
3.3.3.7. ë©í í´ëì¤ì ì©ë¶
ë©í í´ëì¤ì ì ì¬ì ì¸ ì©ëìë íê³ê° ììµëë¤. íì ë ëª ê°ì§ ìì´ëì´ë¤ìë enum, ë¡ê¹ , ì¸í°íì´ì¤ ê²ì¬, ìëíë ìì(automatic delegation), ìëíë íë¡í¼í°(properety) ìì±, íë½ì(proxy), íë ìì(framework), ìëíë ìì ë¡í¹/ë기í(automatic resource locking/synchronization) ë±ì´ ììµëë¤.
3.3.4. ì¸ì¤í´ì¤ ë° ìë¸ í´ëì¤ ê²ì¬ 커ì¤í°ë§ì´ì ì´ì ¶
ë¤ì ë©ìëë¤ì isinstance() ì issubclass() ë´ì¥ í¨ìë¤ì 기본 ëìì ì¬ì ìíë ë° ì¬ì©ë©ëë¤.
í¹í, ë©í í´ëì¤ abc.ABCMeta ë ì¶ì ë² ì´ì¤ í´ëì¤(Abstract Base Class, ABC)를 ë¤ë¥¸ ABC를 í¬í¨í ììì í´ëì¤ë í(ë´ì¥íì í¬í¨í©ëë¤)ì âê°ì ë² ì´ì¤ í´ëì¤(virtual base class)âë¡ ì¶ê°í ì ìê² íë ¤ê³ ì´ ë©ìëë¤ì 구íí©ëë¤.
- type.__instancecheck__(self, instance)¶
instance ê° (ì§ì ì ì´ê±°ë ê°ì ì ì¼ë¡) class ì ì¸ì¤í´ì¤ë¡ ì·¨ê¸ë ì ìì¼ë©´ ì°¸ì ëë ¤ì¤ëë¤. ë§ì½ ì ìëë©´,
isinstance(instance, class)를 구íí기 ìí´ í¸ì¶ë©ëë¤.
- type.__subclasscheck__(self, subclass)¶
subclass ê° (ì§ì ì ì´ê±°ë ê°ì ì ì¼ë¡) class ì ìë¸ í´ëì¤ë¡ ì·¨ê¸ë ì ìì¼ë©´ ì°¸ì ëë ¤ì¤ëë¤. ë§ì½ ì ìëë©´,
issubclass(subclass, class)를 구íí기 ìí´ í¸ì¶ë©ëë¤.
ì´ ë©ìëë¤ì í´ëì¤ì í(ë©í í´ëì¤)ìì ì¡°íëë¤ë ê²ì 주ìí´ì¼ í©ëë¤. ì¤ì í´ëì¤ìì í´ëì¤ ë©ìëë¡ ì ìë ì ììµëë¤. ì´ê²ì ì¸ì¤í´ì¤ì ëí´ í¸ì¶ëë í¹ì ë©ìëë¤ì ì¡°íì ì¼ê´ì± ììµëë¤. ì´ ê²½ì° ì¸ì¤í´ì¤ë í´ëì¤ ìì²´ë¤.
ë 보기
- PEP 3119 - ì¶ì ë² ì´ì¤ í´ëì¤ì ëì
Includes the specification for customizing
isinstance()andissubclass()behavior through__instancecheck__()and__subclasscheck__(), with motivation for this functionality in the context of adding Abstract Base Classes (see theabcmodule) to the language.
3.3.5. ì ë¤ë¦ í íë´ ë´ê¸°Â¶
When using type annotations, it is often useful to
parameterize a generic type using Pythonâs square-brackets notation.
For example, the annotation list[int] might be used to signify a
list in which all the elements are of type int.
ë 보기
- PEP 484 - Type Hints
Introducing Pythonâs framework for type annotations
- Generic Alias Types
Documentation for objects representing parameterized generic classes
- ì ë¤ë¦, user-defined generics and
typing.Generic Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.
A class can generally only be parameterized if it defines the special
class method __class_getitem__().
- classmethod object.__class_getitem__(cls, key)¶
key ì ìë í ì¸ìì ìí ì ë¤ë¦ í´ëì¤ì í¹ìí를 ëíë´ë ê°ì²´ë¥¼ ëë ¤ì¤ëë¤.
When defined on a class,
__class_getitem__()is automatically a class method. As such, there is no need for it to be decorated with@classmethodwhen it is defined.
3.3.5.1. The purpose of __class_getitem__¶
The purpose of __class_getitem__() is to allow runtime
parameterization of standard-library generic classes in order to more easily
apply type hints to these classes.
To implement custom generic classes that can be parameterized at runtime and
understood by static type-checkers, users should either inherit from a standard
library class that already implements __class_getitem__(), or
inherit from typing.Generic, which has its own implementation of
__class_getitem__().
Custom implementations of __class_getitem__() on classes defined
outside of the standard library may not be understood by third-party
type-checkers such as mypy. Using __class_getitem__() on any class for
purposes other than type hinting is discouraged.
3.3.5.2. __class_getitem__ versus __getitem__¶
Usually, the subscription of an object using square
brackets will call the __getitem__() instance method defined on
the objectâs class. However, if the object being subscribed is itself a class,
the class method __class_getitem__() may be called instead.
__class_getitem__() should return a GenericAlias
object if it is properly defined.
Presented with the expression obj[x], the Python interpreter
follows something like the following process to decide whether
__getitem__() or __class_getitem__() should be
called:
from inspect import isclass
def subscribe(obj, x):
"""Return the result of the expression 'obj[x]'"""
class_of_obj = type(obj)
# If the class of obj defines __getitem__,
# call class_of_obj.__getitem__(obj, x)
if hasattr(class_of_obj, '__getitem__'):
return class_of_obj.__getitem__(obj, x)
# Else, if obj is a class and defines __class_getitem__,
# call obj.__class_getitem__(x)
elif isclass(obj) and hasattr(obj, '__class_getitem__'):
return obj.__class_getitem__(x)
# Else, raise an exception
else:
raise TypeError(
f"'{class_of_obj.__name__}' object is not subscriptable"
)
In Python, all classes are themselves instances of other classes. The class of
a class is known as that classâs metaclass, and most classes have the
type class as their metaclass. type does not define
__getitem__(), meaning that expressions such as list[int],
dict[str, float] and tuple[str, bytes] all result in
__class_getitem__() being called:
>>> # list has class "type" as its metaclass, like most classes:
>>> type(list)
<class 'type'>
>>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
True
>>> # "list[int]" calls "list.__class_getitem__(int)"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type(list[int])
<class 'types.GenericAlias'>
However, if a class has a custom metaclass that defines
__getitem__(), subscribing the class may result in different
behaviour. An example of this can be found in the enum module:
>>> from enum import Enum
>>> class Menu(Enum):
... """A breakfast menu"""
... SPAM = 'spam'
... BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type(Menu)
<class 'enum.EnumMeta'>
>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']
<Menu.SPAM: 'spam'>
>>> type(Menu['SPAM'])
<enum 'Menu'>
ë 보기
- PEP 560 - Core Support for typing module and generic types
Introducing
__class_getitem__(), and outlining when a subscription results in__class_getitem__()being called instead of__getitem__()
3.3.6. ì½ë¬ë¸ ê°ì²´ íë´ ë´ê¸°Â¶
3.3.7. 컨í ì´ëí íë´ ë´ê¸°Â¶
The following methods can be defined to implement container objects. None of them
are provided by the object class itself. Containers usually are
sequences (such as lists or
tuples) or mappings (like
dictionaries),
but can represent other containers as well. The first set of methods is used
either to emulate a sequence or to emulate a mapping; the difference is that for
a sequence, the allowable keys should be the integers k for which 0 <= k <
N where N is the length of the sequence, or slice objects, which define a
range of items. It is also recommended that mappings provide the methods
keys(), values(), items(), get(), clear(),
setdefault(), pop(), popitem(), copy(), and
update() behaving similar to those for Pythonâs standard dictionary
objects. The collections.abc module provides a
MutableMapping
abstract base class to help create those methods from a base set of
__getitem__(), __setitem__(),
__delitem__(), and keys().
Mutable sequences should provide methods
append(), clear(), count(),
extend(), index(), insert(),
pop(), remove(), and reverse(),
like Python standard list objects.
Finally, sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
__add__(), __radd__(), __iadd__(),
__mul__(), __rmul__() and __imul__()
described below; they should not define other numerical
operators.
It is recommended that both mappings and sequences implement the
__contains__() method to allow efficient use of the in
operator; for
mappings, in should search the mappingâs keys; for sequences, it should
search through the values. It is further recommended that both mappings and
sequences implement the __iter__() method to allow efficient iteration
through the container; for mappings, __iter__() should iterate
through the objectâs keys; for sequences, it should iterate through the values.
- object.__len__(self)¶
Called to implement the built-in function
len(). Should return the length of the object, an integer>=0. Also, an object that doesnât define a__bool__()method and whose__len__()method returns zero is considered to be false in a Boolean context.CPython 구í ìì¸: In CPython, the length is required to be at most
sys.maxsize. If the length is larger thansys.maxsizesome features (such aslen()) may raiseOverflowError. To prevent raisingOverflowErrorby truth value testing, an object must define a__bool__()method.
- object.__length_hint__(self)¶
Called to implement
operator.length_hint(). Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer>=0. The return value may also beNotImplemented, which is treated the same as if the__length_hint__method didnât exist at all. This method is purely an optimization and is never required for correctness.Added in version 3.4.
- object.__getitem__(self, subscript)¶
Called to implement subscription, that is,
self[subscript]. See Subscriptions and slicings for details on the syntax.There are two types of built-in objects that support subscription via
__getitem__():sequences, where subscript (also called index) should be an integer or a
sliceobject. See the sequence documentation for the expected behavior, including handlingsliceobjects and negative indices.mappings, where subscript is also called the key. See mapping documentation for the expected behavior.
If subscript is of an inappropriate type,
__getitem__()should raiseTypeError. If subscript has an inappropriate value,__getitem__()should raise anLookupErroror one of its subclasses (IndexErrorfor sequences;KeyErrorfor mappings).ì°¸ê³
Slicing is handled by
__getitem__(),__setitem__(), and__delitem__(). A call likea[1:2] = b
ê³¼ ê°ì í¸ì¶ì
a[slice(1, 2, None)] = b
and so forth. Missing slice items are always filled in with
None.ì°¸ê³
The sequence iteration protocol (used, for example, in
forloops), expects that anIndexErrorwill be raised for illegal indexes to allow proper detection of the end of a sequence.ì°¸ê³
When subscripting a class, the special class method
__class_getitem__()may be called instead of__getitem__(). See __class_getitem__ versus __getitem__ for more details.
- object.__setitem__(self, key, value)¶
self[key]ë¡ì ëì ì 구íí기 ìí´ í¸ì¶ë©ëë¤.__getitem__()ê³¼ ê°ì 주ìê° íìí©ëë¤. 매íì ê²½ì°ìë, ê°ì²´ê° í¤ì ëí´ ê°ì ë³ê²½ì´ë ì í¤ì ì¶ê°ë¥¼ íë½í ê²½ì°, ìíì¤ì ê²½ì°ë íëª©ì´ êµì²´ë ì ìì ëë§ êµ¬íëì´ì¼ í©ëë¤. ì못ë key ê°ì ê²½ì°ë__getitem__()ììì ê°ì ìì¸ë¥¼ ì¼ì¼ì¼ì¼ í©ëë¤.
- object.__delitem__(self, key)¶
self[key]ì ìì 를 구íí기 ìí´ í¸ì¶ë©ëë¤.__getitem__()ê³¼ ê°ì 주ìê° íìí©ëë¤. 매íì ê²½ì°ìë, ê°ì²´ê° í¤ì ìì 를 íë½í ê²½ì°, ìíì¤ì ê²½ì°ë íëª©ì´ ìíì¤ë¡ë¶í° ì ê±°ë ì ìì ëë§ êµ¬íëì´ì¼ í©ëë¤. ì못ë key ê°ì ê²½ì°ë__getitem__()ììì ê°ì ìì¸ë¥¼ ì¼ì¼ì¼ì¼ í©ëë¤.
- object.__missing__(self, key)¶
dict.__getitem__()ì´ dict ìë¸ í´ëì¤ìì í¤ê° ëì ë리ì ìì¼ë©´self[key]를 구íí기 ìí´ í¸ì¶í©ëë¤.
- object.__iter__(self)¶
This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.
- object.__reversed__(self)¶
reversed()ë´ì¥ í¨ìê° ì ì´í°ë ì´ì (reverse iteration)ì 구íí기 ìí´ (ìë¤ë©´) í¸ì¶í©ëë¤. 컨í ì´ëì ìë ê°ì²´ë¤ì ì ìì¼ë¡ íìíë ì ì´í°ë ì´í° ê°ì²´ë¥¼ ëë ¤ì¤ì¼ í©ëë¤.__reversed__()ë©ìëê° ì ê³µëì§ ìì¼ë©´,reversed()ë´ì¥í¨ìë ìíì¤ íë¡í ì½(__len__()ê³¼__getitem__())ì ëìì¼ë¡ ì¬ì©í©ëë¤. ìíì¤ íë¡í ì½ì ì§ìíë ê°ì²´ë¤ìreversed()ê° ì ê³µíë ê²ë³´ë¤ ë í¨ì¨ì ì¸ êµ¬íì ì ê³µí ì ìì ëë§__reversed__()를 ì ê³µí´ì¼ í©ëë¤.
멤ë²ì ê²ì¬ ì°ì°ìë¤(in ê³¼ not in) ì ë³´íµ ì»¨í
ì´ëì ëí ì´í°ë ì´ì
ì¼ë¡ 구íë©ëë¤. íì§ë§, 컨í
ì´ë ê°ì²´ë ë í¨ì¨ì ì¸ êµ¬íì ë¤ìê³¼ ê°ì í¹ì ë©ìë를 íµí´ ì ê³µí ì ììµëë¤. ì´ ê²½ì° ê°ì²´ë ì´í°ë¬ë¸ì¼ íìë ììµëë¤.
- object.__contains__(self, item)¶
멤ë²ì ê²ì¬ ì°ì°ì를 구íí기 ìí´ í¸ì¶ë©ëë¤. item ì´ self ì ìì¼ë©´ ì°¸ì, ê·¸ë ì§ ìì¼ë©´ ê±°ì§ì ëë ¤ì¤ì¼ í©ëë¤. 매í ê°ì²´ì ê²½ì°, í¤-ê° ìì´ ìëë¼ ë§¤íì í¤ê° ê³ ë ¤ëì´ì¼ í©ëë¤.
__contains__()를 ì ìíì§ ìë ê°ì²´ì ê²½ì°, 멤ë²ì ê²ì¬ë 먼ì __iter__()를 íµí ì´í°ë ì´ì ì ìëí í,__getitem__()ì íµí ë¡ì ìíì¤ ì´í°ë ì´ì íë¡í ì½ì ìëí©ëë¤. ì¸ì´ ë í¼ë°ì¤ì ì´ ì ì ì°¸ê³ íììì¤.
3.3.8. ì«ì í íë´ ë´ê¸°Â¶
ì«ì íì íë´ ë´ê¸° ìí´ ë¤ìê³¼ ê°ì ë©ìëë¤ì ì ìí ì ììµëë¤. 구íëë í¹ë³í ì¢ ë¥ì ì«ìì ìí´ ì§ìëì§ ìë ì°ì°ë¤(ì를 ë¤ì´, ì ìê° ìë ì«ìë¤ì ëí ë¹í¸ ì°ì°ë¤)ì ëìíë ë©ìëë¤ì ì ìëì§ ìì ì±ë¡ ë¨ê²¨ëì´ì¼ í©ëë¤.
- object.__add__(self, other)¶
- object.__sub__(self, other)¶
- object.__mul__(self, other)¶
- object.__matmul__(self, other)¶
- object.__truediv__(self, other)¶
- object.__floordiv__(self, other)¶
- object.__mod__(self, other)¶
- object.__divmod__(self, other)¶
- object.__pow__(self, other[, modulo])¶
- object.__lshift__(self, other)¶
- object.__rshift__(self, other)¶
- object.__and__(self, other)¶
- object.__xor__(self, other)¶
- object.__or__(self, other)¶
These methods are called to implement the binary arithmetic operations (
+,-,*,@,/,//,%,divmod(),pow(),**,<<,>>,&,^,|). For instance, to evaluate the expressionx + y, where x is an instance of a class that has an__add__()method,type(x).__add__(x, y)is called. The__divmod__()method should be the equivalent to using__floordiv__()and__mod__(); it should not be related to__truediv__(). Note that__pow__()should be defined to accept an optional third argument if the three-argument version of the built-inpow()function is to be supported.If one of those methods does not support the operation with the supplied arguments, it should return
NotImplemented.
- object.__radd__(self, other)¶
- object.__rsub__(self, other)¶
- object.__rmul__(self, other)¶
- object.__rmatmul__(self, other)¶
- object.__rtruediv__(self, other)¶
- object.__rfloordiv__(self, other)¶
- object.__rmod__(self, other)¶
- object.__rdivmod__(self, other)¶
- object.__rpow__(self, other[, modulo])¶
- object.__rlshift__(self, other)¶
- object.__rrshift__(self, other)¶
- object.__rand__(self, other)¶
- object.__rxor__(self, other)¶
- object.__ror__(self, other)¶
These methods are called to implement the binary arithmetic operations (
+,-,*,@,/,//,%,divmod(),pow(),**,<<,>>,&,^,|) with reflected (swapped) operands. These functions are only called if the operands are of different types, when the left operand does not support the corresponding operation [3], or the right operandâs class is derived from the left operandâs class. [4] For instance, to evaluate the expressionx - y, where y is an instance of a class that has an__rsub__()method,type(y).__rsub__(y, x)is called iftype(x).__sub__(x, y)returnsNotImplementedortype(y)is a subclass oftype(x). [5]Note that
__rpow__()should be defined to accept an optional third argument if the three-argument version of the built-inpow()function is to be supported.ë²ì 3.14ìì ë³ê²½: Three-argument
pow()now try calling__rpow__()if necessary. Previously it was only called in two-argumentpow()and the binary power operator.ì°¸ê³
ë§ì½ ì¤ë¥¸ìª½ í¼ì°ì°ìì íì´ ì¼ìª½ í¼ì°ì°ìì íì ìë¸ í´ëì¤ì´ê³ , ê·¸ ìë¸ í´ëì¤ê° ì°ì°ì ë¤ì§í ë©ìëì ë¤ë¥¸ 구íì ì ê³µíë©´, ì´ ë©ìëê° ì¼ìª½ ì°ì°ìì ë¤ì§íì§ ìì ë©ìëë³´ë¤ ë¨¼ì í¸ì¶ë©ëë¤. ì´ ëìì ìë¸ í´ëì¤ê° ì¡°ìë¤ì ì°ì°ì ì¬ì ìí ì ìëë¡ í©ëë¤.
- object.__iadd__(self, other)¶
- object.__isub__(self, other)¶
- object.__imul__(self, other)¶
- object.__imatmul__(self, other)¶
- object.__itruediv__(self, other)¶
- object.__ifloordiv__(self, other)¶
- object.__imod__(self, other)¶
- object.__ipow__(self, other[, modulo])¶
- object.__ilshift__(self, other)¶
- object.__irshift__(self, other)¶
- object.__iand__(self, other)¶
- object.__ixor__(self, other)¶
- object.__ior__(self, other)¶
These methods are called to implement the augmented arithmetic assignments (
+=,-=,*=,@=,/=,//=,%=,**=,<<=,>>=,&=,^=,|=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, or if that method returnsNotImplemented, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an__iadd__()method,x += yis equivalent tox = x.__iadd__(y). If__iadd__()does not exist, or ifx.__iadd__(y)returnsNotImplemented,x.__add__(y)andy.__radd__(x)are considered, as with the evaluation ofx + y. In certain situations, augmented assignment can result in unexpected errors (see ë§ì ì ìëíëë°, ì a_tuple[i] += [âitemâ]ì´ ìì¸ë¥¼ ì¼ì¼íµëê¹?), but this behavior is in fact part of the data model.
- object.__neg__(self)¶
- object.__pos__(self)¶
- object.__abs__(self)¶
- object.__invert__(self)¶
ì¼ í ì°ì ì°ì°(
-,+,abs(),~)ì 구íí기 ìí´ í¸ì¶ë©ëë¤.
- object.__complex__(self)¶
- object.__int__(self)¶
- object.__float__(self)¶
ë´ì¥ í¨ì
complex(),int(),float()를 구íí기 ìí´ í¸ì¶ë©ëë¤. ì ì í íì ê°ì ëë ¤ì¤ì¼ í©ëë¤.
- object.__index__(self)¶
operator.index()를 구íí기 ìí´ í¸ì¶ëê³ , íì´ì¬ì´ ì«ì ê°ì²´ë¥¼ ì ì ê°ì²´ë¡ ìì¤ ìì´ ë³íí´ì¼ í ë(ì¬ë¼ì´ì±ì´ë ë´ì¥bin(),hex(),oct()í¨ìë¤ìììê°ì´)ë§ë¤ í¸ì¶ë©ëë¤. ì´ ë©ìëì ì¡´ì¬ë ì«ì ê°ì²´ê° ì ì íìì ê°ë¦¬íµëë¤. ë°ëì ì ì를 ëë ¤ì¤ì¼ í©ëë¤.__int__(),__float__()ë°__complex__()ê° ì ìëì´ ìì§ ìì¼ë©´, í´ë¹ ë´ì¥ í¨ìint(),float()ë°complex()ë__index__()를 ì¬ì©í©ëë¤.
- object.__round__(self[, ndigits])¶
- object.__trunc__(self)¶
- object.__floor__(self)¶
- object.__ceil__(self)¶
ë´ì¥ í¨ì
round()ìmathí¨ìtrunc(),floor(),ceil()ì 구íí기 ìí´ í¸ì¶ë©ëë¤. ndigits ê°__round__()ë¡ ì ë¬ëì§ ìë í, ì´ ë©ìëë¤ì 모ëIntegral(ë³´íµint) ë¡ ì린 ê°ì²´ì ê°ì ëë ¤ì¤ì¼ í©ëë¤.ë²ì 3.14ìì ë³ê²½:
int()no longer delegates to the__trunc__()method.
3.3.9. with 문 컨í ì¤í¸ ê´ë¦¬ì¶
컨í
ì¤í¸ ê´ë¦¬ì (context manager) ë with 문ì ì¤íí ë ì리 ì¡ë ì¤í 컨í
ì¤í¸(context)를 ì ìíë ê°ì²´ì
ëë¤. ì½ë ë¸ë¡ì ì¤íì ìí´, 컨í
ì¤í¸ ê´ë¦¬ìë ìíë ì¤íìê° ì»¨í
ì¤í¸ë¡ì ì§ì
ê³¼ íì¶ì ì²ë¦¬í©ëë¤. 컨í
ì¤í¸ ê´ë¦¬ìë ë³´íµ with 문(with 문 ì¹ì
ìì ì¤ëª
í©ëë¤)ì¼ë¡ ììëì§ë§, ê·¸ë¤ì ë©ìë를 í¸ì¶í´ì ì§ì ì¬ì©í ìë ììµëë¤.
컨í ì¤í¸ ê´ë¦¬ìì ì íì ì¸ ì©ëìë ë¤ìí ì¢ ë¥ì ì ì ìí(global state)를 ë³´ê´íê³ ë³µêµ¬íë ê², ììì ë¡í¹(locking)íê³ ì¸ë¡í¹(unlocking)íë ê², ì´ë¦° íì¼ì ë«ë ê² ë±ì´ ììµëë¤.
For more information on context managers, see 컨í
ì¤í¸ ê´ë¦¬ì í.
The object class itself does not provide the context manager methods.
- object.__enter__(self)¶
ì´ ê°ì²´ì ì°ê´ë ì¤íìê° ì»¨í ì¤í¸ì ì§ì í©ëë¤.
with문ìasì ë¡ ì§ì ë ëìì´ ìë¤ë©´, ì´ ë©ìëì ë°í ê°ì ì°ê²°í©ëë¤.
- object.__exit__(self, exc_type, exc_value, traceback)¶
ì´ ê°ì²´ì ì°ê´ë ì¤íìê° ì»¨í ì¤í¸ë¥¼ ì¢ ë£í©ëë¤. 매ê°ë³ìë¤ì 컨í ì¤í¸ìì ë²ì´ëê² ë§ë ìì¸ë¥¼ 기ì í©ëë¤. ë§ì½ 컨í ì¤í¸ê° ìì¸ ìì´ ì¢ ë£íë¤ë©´, ì¸ ì¸ì 모ë
Noneì´ ë©ëë¤.ë§ì½ ìì¸ê° ì ê³µëê³ , ë©ìëê° ìì¸ë¥¼ ì¤ì§ìí¤ê³ ì¶ì¼ë©´ (ì¦ íì°íë ê²ì ë§ì¼ë ¤ë©´) ì°¸(true)ì ëë ¤ì¤ì¼ í©ëë¤. ê·¸ë ì§ ìì¼ë©´ ìì¸ë ì´ ë©ìëê° ì¢ ë£í íì ê³ì ì§íë©ëë¤.
Note that
__exit__()methods should not reraise the passed-in exception; this is the callerâs responsibility.
3.3.10. Customizing positional arguments in class pattern matching¶
When using a class name in a pattern, positional arguments in the pattern are not
allowed by default, i.e. case MyClass(x, y) is typically invalid without special
support in MyClass. To be able to use that kind of pattern, the class needs to
define a __match_args__ attribute.
- object.__match_args__¶
This class variable can be assigned a tuple of strings. When this class is used in a class pattern with positional arguments, each positional argument will be converted into a keyword argument, using the corresponding value in __match_args__ as the keyword. The absence of this attribute is equivalent to setting it to
().
For example, if MyClass.__match_args__ is ("left", "center", "right") that means
that case MyClass(x, y) is equivalent to case MyClass(left=x, center=y). Note
that the number of arguments in the pattern must be smaller than or equal to the number
of elements in __match_args__; if it is larger, the pattern match attempt will raise
a TypeError.
Added in version 3.10.
ë 보기
- PEP 634 - Structural Pattern Matching
The specification for the Python
matchstatement.
3.3.11. Emulating buffer types¶
The buffer protocol provides a way for Python
objects to expose efficient access to a low-level memory array. This protocol
is implemented by builtin types such as bytes and memoryview,
and third-party libraries may define additional buffer types.
While buffer types are usually implemented in C, it is also possible to implement the protocol in Python.
- object.__buffer__(self, flags)¶
Called when a buffer is requested from self (for example, by the
memoryviewconstructor). The flags argument is an integer representing the kind of buffer requested, affecting for example whether the returned buffer is read-only or writable.inspect.BufferFlagsprovides a convenient way to interpret the flags. The method must return amemoryviewobject.Thread safety: In free-threaded Python, implementations must manage any internal export counter using atomic operations. The method must be safe to call concurrently from multiple threads, and the returned bufferâs underlying data must remain valid until the corresponding
__release_buffer__()call completes. See Thread safety for memoryview objects for details.
- object.__release_buffer__(self, buffer)¶
Called when a buffer is no longer needed. The buffer argument is a
memoryviewobject that was previously returned by__buffer__(). The method must release any resources associated with the buffer. This method should returnNone.Thread safety: In free-threaded Python, any export counter decrement must use atomic operations. Resource cleanup must be thread-safe, as the final release may race with concurrent releases from other threads.
Buffer objects that do not need to perform any cleanup are not required to implement this method.
Added in version 3.12.
ë 보기
- PEP 688 - Making the buffer protocol accessible in Python
Introduces the Python
__buffer__and__release_buffer__methods.collections.abc.BufferABC for buffer types.
3.3.12. Annotations¶
Functions, classes, and modules may contain annotations, which are a way to associate information (usually type hints) with a symbol.
- object.__annotations__¶
This attribute contains the annotations for an object. It is lazily evaluated, so accessing the attribute may execute arbitrary code and raise exceptions. If evaluation is successful, the attribute is set to a dictionary mapping from variable names to annotations.
ë²ì 3.14ìì ë³ê²½: Annotations are now lazily evaluated.
- object.__annotate__(format)¶
An annotate function. Returns a new dictionary object mapping attribute/parameter names to their annotation values.
Takes a format parameter specifying the format in which annotations values should be provided. It must be a member of the
annotationlib.Formatenum, or an integer with a value corresponding to a member of the enum.If an annotate function doesnât support the requested format, it must raise
NotImplementedError. Annotate functions must always supportVALUEformat; they must not raiseNotImplementedError()when called with this format.When called with
VALUEformat, an annotate function may raiseNameError; it must not raiseNameErrorwhen called requesting any other format.If an object does not have any annotations,
__annotate__should preferably be set toNone(it canât be deleted), rather than set to a function that returns an empty dict.Added in version 3.14.
ë 보기
- PEP 649 â Deferred evaluation of annotation using descriptors
Introduces lazy evaluation of annotations and the
__annotate__function.
3.3.13. í¹ì ë©ìë ì¡°í¶
ì¬ì©ì ì ì í´ëì¤ì ê²½ì°, 묵ìì ì¸ í¹ì ë©ìëì í¸ì¶ì ê°ì²´ì ì¸ì¤í´ì¤ ëì ëë¦¬ê° ìë ê°ì²´ì íì ì ìëì´ ìì ëë§ ì¬ë°ë¥´ê² ëìí¨ì´ ë³´ì¥ë©ëë¤. ì´ë° ëìì ë¤ìê³¼ ê°ì ì½ëê° ìì¸ë¥¼ ì¼ì¼í¤ë ìì¸ì ëë¤:
>>> class C:
... pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()
The rationale behind this behaviour lies with a number of special methods such
as __hash__() and __repr__() that are implemented
by all objects,
including type objects. If the implicit lookup of these methods used the
conventional lookup process, they would fail when invoked on the type object
itself:
>>> 1 .__hash__() == hash(1)
True
>>> int.__hash__() == hash(int)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor '__hash__' of 'int' object needs an argument
í´ëì¤ì ì°ê²°ëì§ ìì ë©ìë를 í¸ì¶íë ¤ë ì´ë° ìì ì못ë ìëë ì¢ ì¢ âë©í í´ëì¤ í¼ë(metaclass confusion)â ì´ë¼ê³ ë¶ë¦¬ê³ , í¹ì ë©ìë를 ì¡°íí ë ì¸ì¤í´ì¤ë¥¼ ì°ííë ë°©ë²ì¼ë¡ í¼í ì ììµëë¤.
>>> type(1).__hash__(1) == hash(1)
True
>>> type(int).__hash__(int) == hash(int)
True
In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
__getattribute__() method even of the objectâs metaclass:
>>> class Meta(type):
... def __getattribute__(*args):
... print("Metaclass getattribute invoked")
... return type.__getattribute__(*args)
...
>>> class C(object, metaclass=Meta):
... def __len__(self):
... return 10
... def __getattribute__(*args):
... print("Class getattribute invoked")
... return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__() # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c) # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c) # Implicit lookup
10
Bypassing the __getattribute__() machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of
special methods (the special method must be set on the class
object itself in order to be consistently invoked by the interpreter).
3.4. ì½ë£¨í´(Coroutines)¶
3.4.1. ì´ì¨ì´í°ë¸ ê°ì²´(Awaitable Objects)¶
An awaitable object generally implements an __await__() method.
Coroutine objects returned from async def functions
are awaitable.
ì°¸ê³
The generator iterator objects returned from generators
decorated with types.coroutine()
are also awaitable, but they do not implement __await__().
- object.__await__(self)¶
Must return an iterator. Should be used to implement awaitable objects. For instance,
asyncio.Futureimplements this method to be compatible with theawaitexpression. Theobjectclass itself is not awaitable and does not provide this method.
Added in version 3.5.
ë 보기
PEP 492 ê° ì´ì¨ì´í°ë¸ ê°ì²´ì ëí ë ìì¸í ì 보를 í¬í¨íê³ ììµëë¤.
3.4.2. ì½ë£¨í´ ê°ì²´(Coroutine Objects)¶
Coroutine objects are awaitable objects.
A coroutineâs execution can be controlled by calling __await__() and
iterating over the result. When the coroutine has finished executing and
returns, the iterator raises StopIteration, and the exceptionâs
value attribute holds the return value. If the
coroutine raises an exception, it is propagated by the iterator. Coroutines
should not directly raise unhandled StopIteration exceptions.
ì½ë£¨í´ì ë¤ìì ëì´íë ë©ìëë¤ ëí ê°ê³ ìëë°, ì ëë ì´í°(ì ëë ì´í°-ì´í°ë ì´í° ë©ìë 를 ë³´ììì¤)ì ê²ë¤ê³¼ ë®ììµëë¤. íì§ë§, ì ëë ì´í°ìë ë¬ë¦¬, ì½ë£¨í´ì ì´í°ë ì´ì ì ì§ì ì§ìíì§ë ììµëë¤.
ë²ì 3.5.2ìì ë³ê²½: ì½ë£¨í´ì ë ë² await íë©´ RuntimeError 를 ì¼ì¼íµëë¤.
- coroutine.send(value)¶
Starts or resumes execution of the coroutine. If value is
None, this is equivalent to advancing the iterator returned by__await__(). If value is notNone, this method delegates to thesend()method of the iterator that caused the coroutine to suspend. The result (return value,StopIteration, or other exception) is the same as when iterating over the__await__()return value, described above.
- coroutine.throw(value)¶
- coroutine.throw(type[, value[, traceback]])
Raises the specified exception in the coroutine. This method delegates to the
throw()method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. The result (return value,StopIteration, or other exception) is the same as when iterating over the__await__()return value, described above. If the exception is not caught in the coroutine, it propagates back to the caller.ë²ì 3.12ìì ë³ê²½: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.
- coroutine.close()¶
ì½ë£¨í´ì´ ìì ì ì 리íê³ ì¢ ë£íëë¡ ë§ëëë¤. ë§ì½ ì½ë£¨í´ì´ ì¼ì ì¤ì§ ì¤ì´ë©´, ì´ ë©ìëë 먼ì ì½ë£¨í´ì´ ì¼ì ì¤ì§ëëë¡ í ì´í°ë ì´í°ì
close()ë©ìëë¡ ììí©ëë¤(ê·¸ë° ë©ìë를 ê°ì§ë ê²½ì°). ê·¸ë° ë¤ì ì¼ì ì¤ì§ì§ì ììGeneratorExit를 ë°ììí¤ëë°, ì½ë£¨í´ì´ ì¦ì ìì ì ì 리íëë¡ ë§ëëë¤. ë§ì§ë§ì¼ë¡ ì½ë£¨í´ì ì¤íì ì¢ ë£íë¤ê³ íìíëë°, ìì§ ììíì§ì¡°ì°¨ ììì ëë ê·¸ë ë¤.ì½ë£¨í´ ê°ì²´ê° íê´´ë ëë ìì íë¡ì¸ì¤ì ë°ë¼ ìëì¼ë¡ ë«íëë¤(closed).
3.4.3. ë¹ë기 ì´í°ë ì´í°(Asynchronous Iterators)¶
ë¹ë기 ì´í°ë ì´í° ë ìì ì __anext__ ë©ìëìì ë¹ë기 ì½ë를 í¸ì¶í ì ììµëë¤.
ë¹ë기 ì´í°ë ì´í°ë async for 문ìì ì¬ì©ë ì ììµëë¤.
The object class itself does not provide these methods.
- object.__aiter__(self)¶
ë¹ë기 ì´í°ë ì´í° ê°ì²´ë¥¼ ëë ¤ì¤ì¼ í©ëë¤.
- object.__anext__(self)¶
ì´í°ë ì´í°ì ë¤ì ê°ì 주ë ì´ì¨ì´í°ë¸ ì ëë ¤ì¤ì¼ í©ëë¤. ì´í°ë ì´ì ì´ ëëë©´
StopAsyncIterationìë¬ë¥¼ ì¼ì¼ì¼ì¼ í©ëë¤.
ë¹ë기 ì´í°ë¬ë¸ ê°ì²´ì ì:
class Reader:
async def readline(self):
...
def __aiter__(self):
return self
async def __anext__(self):
val = await self.readline()
if val == b'':
raise StopAsyncIteration
return val
Added in version 3.5.
ë²ì 3.7ìì ë³ê²½: Prior to Python 3.7, __aiter__() could return an awaitable
that would resolve to an
asynchronous iterator.
Starting with Python 3.7, __aiter__() must return an
asynchronous iterator object. Returning anything else
will result in a TypeError error.
3.4.4. ë¹ë기 컨í ì¤í¸ ê´ë¦¬ì¶
ë¹ë기 컨í
ì¤í¸ ê´ë¦¬ì(asynchronous context manager) ë __aenter__ ì __aexit__ ë©ìëìì ì¤íì ì¼ì ì¤ì§í ì ìë 컨í
ì¤í¸ ê´ë¦¬ì ì
ëë¤.
ë¹ë기 컨í
ì¤í¸ ê´ë¦¬ìë async with 문ìì ì¬ì©ë ì ììµëë¤.
The object class itself does not provide these methods.
- object.__aenter__(self)¶
Semantically similar to
__enter__(), the only difference being that it must return an awaitable.
- object.__aexit__(self, exc_type, exc_value, traceback)¶
Semantically similar to
__exit__(), the only difference being that it must return an awaitable.
ë¹ë기 컨í ì¤í¸ ê´ë¦¬ì í´ëì¤ì ì:
class AsyncContextManager:
async def __aenter__(self):
await log('entering context')
async def __aexit__(self, exc_type, exc, tb):
await log('exiting context')
Added in version 3.5.
ê°ì£¼