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.
ãã¹ãŠã®ãªããžã§ã¯ãã¯ãåäžæ§ (identity)ãåãå€ããã£ãŠããŸãã åäžæ§ ã¯çæãããããšã¯å€æŽãããŸãããããã¯ãªããžã§ã¯ãã®ã¢ãã¬ã¹ã®ãããªãã®ã ãšèãããããããããŸããã is æŒç®åã¯2ã€ã®ãªããžã§ã¯ãã®åäžæ§ãæ¯èŒããŸãã id() 颿°ã¯åäžæ§ãè¡šãæŽæ°ãè¿ããŸãã
CPython ã§ã¯ãid(x) 㯠x ãæ ŒçŽãããŠããã¡ã¢ãªäžã®ã¢ãã¬ã¹ãè¿ããŸãã
ãªããžã§ã¯ãã®åã¯ãªããžã§ã¯ãããµããŒãããæäœ (äŸ: len() ããµããŒãããã) ãšããªããžã§ã¯ããåãããå€ã決å®ããŸãã type() 颿°ã¯ãªããžã§ã¯ãã®å (åèªäœããªããžã§ã¯ãã§ã) ãè¿ããŸããåäžæ§ãšåããããªããžã§ã¯ãã®å(type) ã倿Žäžå¯èœã§ãã [1]
ãªããžã§ã¯ãã«ãã£ãŠã¯ å€ ã倿Žããããšãå¯èœã§ããå€ã倿Žã§ãããªããžã§ã¯ãã®ããšã mutable ãšåŒã³ãŸããçæåŸã«å€ã倿Žã§ããªããªããžã§ã¯ãã®ããšã immutable ãšåŒã³ãŸãã(mutable ãªãªããžã§ã¯ããžã®åç §ãæ ŒçŽããŠãã immutableãªã³ã³ãããªããžã§ã¯ãã®å€ã¯ããã®æ ŒçŽããŠãããªããžã§ã¯ãã®å€ãå€åããæã«å€åããŸãããã³ã³ãããã©ã®ãªããžã§ã¯ããæ ŒçŽããŠããã®ããå€åããªãã®ã§ããã° immutable ã ãšèããããšãã§ããŸãããããã£ãŠãimmutable ãã©ããã¯å€ã倿Žå¯èœãã©ãããšå®å šã«äžèŽããããã§ã¯ãããŸãã) ãªããžã§ã¯ãã mutable ãã©ããã¯ãã®åã«ãã£ãŠæ±ºãŸããŸããäŸãã°ãæ°å€åãæåååãšã¿ãã«åã®ã€ã³ã¹ã¿ã³ã¹ã¯ immutable ã§ãdict ã list 㯠mutable ã§ãã
ãªããžã§ã¯ããæç€ºçã«ç Žå£ããããšã¯ã§ããŸãã; ãããããªããžã§ã¯ãã«å°éäžèœ (unreachable) ã«ãªããšãã¬ããŒãžã³ã¬ã¯ã·ã§ã³ (garbage-collection) ã«ãã£ãŠåŠçããããããããŸãããã¬ããŒãžã³ã¬ã¯ã·ã§ã³ãé ãããããå šãè¡ããªãå®è£ ãèš±ãããŠããŸã --- å°éå¯èœãªãªããžã§ã¯ããåŠçããŠããŸããªãããããã¬ããŒãžã³ã¬ã¯ã·ã§ã³ãã©ãå®è£ ãããã¯å®è£ å質ã®åé¡ã§ãã
çŸåšã® CPython å®è£
ã§ã¯åç
§ã«ãŠã³ã (reference-counting) æ¹åŒã䜿ã£ãŠããã(ãªãã·ã§ã³ãšããŠ) 埪ç°åç
§ãè¡ã£ãŠããã¬ããŒãžãªããžã§ã¯ããé
å»¶æ€åºããŸãããã®å®è£
ã§ã¯ã»ãšãã©ã®ãªããžã§ã¯ããå°éäžèœã«ãªããšåæã«åŠçããããšãã§ããŸããã埪ç°åç
§ãå«ãã¬ããŒãžãªããžã§ã¯ãã®åéã確å®ã«è¡ãããããä¿èšŒããŠããããã§ã¯ãããŸããã埪ç°åç
§ãæã€ã¬ããŒãžãªããžã§ã¯ãåéã®å¶åŸ¡ã«ã€ããŠã¯ã gc ã¢ãžã¥ãŒã«ãåç
§ããŠãã ããã CPython以å€ã®å®è£
ã¯å¥ã®æ¹åŒã䜿ã£ãŠãããCPythonãå°æ¥ã¯å¥ã®æ¹åŒã䜿ããããããŸããããªããžã§ã¯ããå°éäžèœã«ãªã£ããšãã«å³åº§ã«çµäºåŠçãããããšã«é Œããªãã§ãã ãã (ã§ããããã¡ã€ã«ã¯å¿
ãæç€ºçã«éããŠãã ãã)ã
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. æšæºåã®é局¶
以äžã¯ Python ã«çµã¿èŸŒãŸããŠããåã®ãªã¹ãã§ãã(å®è£ ã«ãã£ãŠãCãJavaããŸãã¯ãã®ä»ã®èšèªã§æžããã) æ¡åŒµã¢ãžã¥ãŒã«ã§ããã®ä»ã®åãå®çŸ©ãããŠããããšããããŸããæ°ããªå (æçæ°ããæŽæ°ãå¹ççã«èšæ¶ããé åããªã©) ã®è¿œå ã¯ããããŠãæšæºã©ã€ãã©ãªãéããŠæäŸãããŸãããå°æ¥ã®ããŒãžã§ã³ã® Python ã§ã¯ãåã®éå±€æ§é ã«ãã®ãããªè¿œå ããªããããããããŸããã
以äžã«èª¬æããåã®ããã€ãã«ã¯ã 'ç¹æ®å±æ§ (special attribute)' ãåæããæ®µèœããããŸãããããã®å±æ§ã¯å®è£ ãžã®ã¢ã¯ã»ã¹ææ®µãæäŸãããã®ã§ãäžè¬çãªçšéã«å©çšããããã®ãã®ã§ã¯ãããŸãããç¹æ®å±æ§ã®å®çŸ©ã¯å°æ¥å€æŽãããå¯èœæ§ããããŸãã
3.2.1. None¶
ãã®åã«ã¯åäžã®å€ãããããŸããããã®å€ãæã€ãªããžã§ã¯ãã¯ãã äžã€ããååšããŸããããã®ãªããžã§ã¯ãã¯çµã¿èŸŒã¿å None ã§ã¢ã¯ã»ã¹ãããŸãããã®ãªããžã§ã¯ãã¯ãæ§ã
ãªç¶æ³ã§å€ãååšããªãããšãããããŸããäŸãã°ãæç€ºçã«å€ãè¿ããªã颿°ã¯ None ãè¿ããŸãã None ã®çå€ (truth value) ã¯åœ (false) ã§ãã
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¶
ãã®åã«ã¯åäžã®å€ãããããŸããããã®å€ãæã€ãªããžã§ã¯ãã¯ãã äžã€ããååšããŸããããã®ãªããžã§ã¯ãã¯ãªãã©ã« ... ãŸãã¯Pythonã§æ±ºããããŠããåå Ellipsis ã§ã¢ã¯ã»ã¹ãããŸããççå€ã¯ç (true)ã§ãã
3.2.4. numbers.Number¶
æ°å€ãªãã©ã«ã«ãã£ãŠäœæãããããç®è¡æŒç®ãçµã¿èŸŒã¿ã®ç®è¡é¢æ°ã«ãã£ãŠè¿ããããªããžã§ã¯ãã§ããæ°å€ãªããžã§ã¯ãã¯å€æŽäžèœã§ã; äžåºŠå€ãçæããããšãäºåºŠãšå€æŽãããããšã¯ãããŸãããPython ã®æ°å€ãªããžã§ã¯ãã¯ãããŸã§ããªãæ°åŠã§èšããšããã®æ°å€ãšåŒ·ãé¢ä¿ããŠããŸãããã³ã³ãã¥ãŒã¿å ã§æ°å€ã衚çŸããéã«äŒŽãå¶éãåããŠããŸãã
__repr__() ãš __str__() ããèšç®ãããæ°å€ã¯ã©ã¹ã®æåå衚çŸã«ã¯æ¬¡ã®ãããªç¹æ§ããããŸã:
ãã®æååã¯ãã¯ã©ã¹ã³ã³ã¹ãã©ã¯ã¿ã«æž¡ãããšãã«ãå ã®æ°å€ã®å€ãæã€ãªããžã§ã¯ããçæããæå¹ãªæ°å€ãªãã©ã«ã§ãã
ã§ãããªãã10ãåºãšããŠè¡šçŸãããŸãã
å°æ°ç¹ã®åã«ãã 1 ã€ã®ãŒããé€ããŠãäžã«é£ãªããŒãã¯è¡šç€ºãããŸããã
å°æ°ç¹ã®åŸã«ãã 1 ã€ã®ãŒããé€ããŠãäžã«é£ãªããŒãã¯è¡šç€ºãããŸããã
笊å·ã¯æ°å€ãè² æ°ã®ãšãã®ã¿è¡šç€ºãããŸãã
Python distinguishes between integers, floating-point numbers, and complex numbers:
3.2.4.1. numbers.Integral (æŽæ°)¶
æŽæ°åã¯ãæŽæ°(æ£ã®æ°ããã³è² ã®æ°)ãè¡šãæ°åŠçéåå ã«ãããèŠçŽ ã衚çŸããåã§ãã
泚é
æŽæ°è¡šçŸã«é¢ããèŠåã¯ãè² ã®æŽæ°ãå«ãã·ããæŒç®ããã¹ã¯æŒç®ã«ãããŠãæãææçŸ©ãªè§£éãã§ããããã«æå³ãããŠããŸãã
æŽæ°ã«ã¯ 2 çš®é¡ãããŸã:
- æŽæ° (
int) ç¡å¶éã®ç¯å²ã®æ°ã衚çŸããŸãããå©çšå¯èœãª (ä»®æ³) ã¡ã¢ãªãµã€ãºã®å¶éã®ã¿ãåããŸããã·ããæŒç®ããã¹ã¯æŒç®ã®ããã«2鲿°è¡šçŸãæã€ãšæ³å®ãããŸããè² ã®æ°ã¯ç¬Šå·ããããå·Šã«ç¡éã«å»¶ã³ãŠãããããªé¯èŠãäžãã 2 ã®è£æ°è¡šçŸã®å€åã§è¡šãããŸãã
- ããŒã«å€ (
bool) çåœå€ã® False ãš True ã衚ããŸãã
FalseãšTrueã衚ã 2 ã€ã®ãªããžã§ã¯ãã®ã¿ãããŒã«å€ãªããžã§ã¯ãã§ããããŒã«åã¯æŽæ°åã®æŽŸçåã§ãããã»ãšãã©ã®ç¶æ³ã§ãããã 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. ã·ãŒã±ã³ã¹å (sequence)¶
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 slice)" ããµããŒãããŠããŸã: a[i:j:k] ã¯ã x = i + n*k, n >= 0 ã〠i <= x < j ã§ãããããªã€ã³ãã¯ã¹ x ãæã€ãã㪠a å
šãŠã®èŠçŽ ãéžæããŸãã
ã·ãŒã±ã³ã¹ã¯ã倿Žå¯èœãªãã®ããããã§ãªããã§åºå¥ãããŠããŸã:
3.2.5.1. 倿Žäžèœãªã·ãŒã±ã³ã¹ (immutable sequence)¶
倿Žäžèœãªã·ãŒã±ã³ã¹åã®ãªããžã§ã¯ãã¯ãäžåºŠçæããããšãã®å€ã倿Žããããšãã§ããŸããã (ãªããžã§ã¯ãã«ä»ã®ãªããžã§ã¯ããžã®åç §ãå ¥ã£ãŠããå Žåãåç §ãããŠãããªããžã§ã¯ãã¯å€æŽå¯èœãªãªããžã§ã¯ãã§ãããããã®å€ã¯å€æŽãããå¯èœæ§ããããŸã; ãããã倿Žäžèœãªãªããžã§ã¯ããçŽæ¥åç §ããŠãããªããžã§ã¯ãã®éåèªäœã¯ã倿Žããããšãã§ããŸããã)
以äžã®åã¯å€æŽäžèœãªã·ãŒã±ã³ã¹åã§ã:
- æååå (string)
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.- ã¿ãã«å (tuple)
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. 倿Žå¯èœãªã·ãŒã±ã³ã¹å (mutable sequence)¶
倿Žå¯èœãªã·ãŒã±ã³ã¹ã¯ãäœæããåŸã§å€æŽããããšãã§ããŸãã倿Žå¯èœãªã·ãŒã±ã³ã¹ã§ã¯ãæ·»å衚èšãã¹ã©ã€ã¹è¡šèšã䜿ã£ãŠæå®ãããèŠçŽ ã«ä»£å
¥ãè¡ãããšãã§ãã del (delete) æã䜿ã£ãŠèŠçŽ ãåé€ããããšãã§ããŸãã
泚é
The collections and array module provide
additional examples of mutable sequence types.
Python ã«æåããçµã¿èŸŒãŸããŠãã倿Žå¯èœãªã·ãŒã±ã³ã¹åã¯ãä»ã®ãšããäºã€ã§ã:
- ãªã¹ãå (list)
ãªã¹ãã®èŠçŽ ã¯ä»»æã® Python ãªããžã§ã¯ãã«ã§ããŸãããªã¹ãã¯ãè§æ¬åŒ§ã®äžã«ã«ã³ãã§åºåãããåŒã䞊ã¹ãŠäœããŸãã (é·ãã 0 ã 1 ã®ã·ãŒã±ã³ã¹ãäœãããã«ç¹æ®ãªå Žååãã¯å¿ èŠãªãããšã«æ³šæããŠãã ããã)
- ãã€ãé å
bytearray ãªããžã§ã¯ãã¯å€æŽå¯èœãªé åã§ããçµã¿èŸŒã¿ã®
bytearray()ã³ã³ã¹ãã©ã¯ã¿ã«ãã£ãŠäœæãããŸãã倿Žå¯èœãªããšãé€ãã° (ã€ãŸãããã·ã¥åã§ããªã)ã byte array ã¯å€æŽäžèœãªbytesãªããžã§ã¯ããšåãã€ã³ã¿ãŒãã§ãŒã¹ãšæ©èœãæäŸããŸãã
3.2.6. éåå¶
éååã¯ãé åºã®ãªãããŠããŒã¯ã§äžå€ãªãªããžã§ã¯ãã®æééåã衚çŸããŸãããã®ããã(é
åã®)æ·»åã䜿ã£ãã€ã³ããã¯ã¹ã¢ã¯ã»ã¹ã¯ã§ããŸããããã ããã€ãã¬ãŒãã¯å¯èœã§ãçµã¿èŸŒã¿é¢æ° len() ã¯éåã®èŠçŽ æ°ãè¿ããŸããéååã®äžè¬çãªäœ¿ãæ¹ã¯ãéåã«å±ããŠãããã®é«éãªãã¹ããã·ãŒã±ã³ã¹ããã®éè€ã®æé€ãå
±ééåã»åéåã»å·®ã»å¯Ÿç§°å·®ãšãã£ãæ°åŠçãªæŒç®ã®èšç®ã§ãã
éåã®èŠçŽ ã«ã¯ãèŸæžã®ããŒãšåãæ®éæ§ã«é¢ããã«ãŒã«ãé©çšãããŸããæ°å€åã¯éåžžã®æ°å€æ¯èŒã®ã«ãŒã«ã«åŸãããšã«æ³šæããŠãã ããããã2ã€ã®æ°å€ã®æ¯èŒçµæãåå€ã§ãã(äŸãã°ã 1 ãš 1.0)ãªãããã®ãã¡ã®1ã€ã®ã¿ãéåã«å«ããããšãã§ããŸãã
çŸåšã2ã€ã®çµã¿èŸŒã¿éååããããŸã:
- éåå
å¯å€ãªéååã§ããçµã¿èŸŒã¿ã®
set()ã³ã³ã¹ãã©ã¯ã¿ã§äœæãããåŸããadd()ãªã©ã®ããã€ãã®ã¡ãœããã§æŽæ°ã§ããŸãã- Frozen set å
äžå€ãªéååã§ããçµã¿èŸŒã¿ã®
frozenset()ã³ã³ã¹ãã©ã¯ã¿ã«ãã£ãŠäœæãããŸãã frozenset ã¯äžå€ã§ ããã·ã¥å¯èœ ãªã®ã§ãå¥ã®éååã®èŠçŽ ã«ãªã£ãããèŸæžã®ããŒã«ããããšãã§ããŸãã
3.2.7. ãããã³ã°å (mapping)¶
ä»»æã®ã€ã³ãã¯ã¹éåã§ã€ã³ãã¯ã¹åãããããªããžã§ã¯ããããªãæéã®éåã衚çŸããŸããæ·»åè¡šèš a[k] ã¯ã k ã§ã€ã³ãã¯ã¹æå®ãããèŠçŽ ã a ããéžæããŸã; éžæãããèŠçŽ ã¯åŒã®äžã§äœ¿ãããšãã§ãã代å
¥ã del æã®å¯Ÿè±¡ã«ããããšãã§ããŸããçµã¿èŸŒã¿é¢æ° len() ã¯ããããã³ã°å
ã®èŠçŽ æ°ãè¿ããŸãã
There is currently a single intrinsic mapping type:
3.2.7.1. èŸæžå (dictionary)¶
ã»ãŒä»»æã®å€ã§ã€ã³ãã¯ã¹ããããªããžã§ã¯ããããªãæéã®éåã衚ããŸãã
ã㌠(key) ãšããŠäœ¿ããªãå€ã®å¯äžã®åã¯ããªã¹ããèŸæžããããŠãªããžã§ã¯ãã®åäžæ§ã§ãªãå€ã§æ¯èŒããããã®ä»ã®å€æŽå¯èœãªåã§ãã
ããã¯ãèŸæžåãå¹ççã«å®è£
ããäžã§ãããŒã®ããã·ã¥å€ãäžå€ã§ããå¿
èŠãããããã§ãã
æ°å€åãããŒã«äœ¿ãå ŽåãããŒå€ã¯éåžžã®æ°å€æ¯èŒã«ãããèŠåã«åŸããŸã: äºã€ã®å€ãçãããªãå Žå (äŸãã° 1 ãš 1.0)ãäºãã«åãèŸæžã®ãšã³ããªã衚ãã€ã³ãã¯ã¹ãšããŠäœ¿ãããšãã§ããŸãã
èŸæžã¯æ¿å ¥ã®é åºãä¿æããŸããã€ãŸããããŒã¯èŸæžã«è¿œå ãããé çªã«çæãããŠãããŸããæ¢åã®ããŒã眮ãæããŠããããŒã®é åºã¯å€ãããŸãããããŒãåé€ããã®ã¡ã«åæ¿å ¥ãããšãå ã®å Žæã§ã¯ãªãèŸæžã®æåŸã«è¿œå ãããŸãã
Dictionaries are mutable; they can be created by the {} notation (see
section èŸæžè¡šç€º).
æ¡åŒµã¢ãžã¥ãŒã« dbm.ndbm ã dbm.gnu ã¯ã collections ã¢ãžã¥ãŒã«ã®ããã«ãå¥ã®ãããã³ã°åã®äŸãæäŸããŠããŸãã
ããŒãžã§ã³ 3.7 ã§å€æŽ: Pythonã®ããŒãžã§ã³3.6ã§ã¯ãèŸæžã¯æ¿å ¥é åºãä¿æããŸããã§ãããCPython 3.6ã§ã¯æ¿å ¥é åºã¯ä¿æãããŸããããããã¯çå®ãããèšèªã®ä»æ§ãšããããããã®åœæã®å®è£ ã®çްéšãšã¿ãªãããŠããŸããã
3.2.8. åŒã³åºãå¯èœå (callable type)¶
颿°åŒã³åºãæäœ (åŒã³åºã (call) åç §) ãè¡ãããšãã§ããåã§ã:
3.2.8.1. ãŠãŒã¶å®çŸ©é¢æ° (user-defined function)¶
ãŠãŒã¶å®çŸ©é¢æ°ãªããžã§ã¯ãã¯ã颿°å®çŸ©ãè¡ãããšã§çæãããŸã (颿°å®çŸ© åç §)ã颿°ã¯ãä»®åŒæ° (formal parameter) ãªã¹ããšåãæ°ã®èŠçŽ ãå ¥ã£ãåŒæ°ãªã¹ããšãšãã«åŒã³åºãããŸãã
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 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. ã€ã³ã¹ã¿ã³ã¹ã¡ãœãã¶
ã€ã³ã¹ã¿ã³ã¹ã¡ãœãããªããžã§ã¯ãã¯ãã¯ã©ã¹ãã¯ã©ã¹ã€ã³ã¹ã¿ã³ã¹ãšä»»æã®åŒã³åºãå¯èœãªããžã§ã¯ã (éåžžã¯ãŠãŒã¶å®çŸ©é¢æ°) ãçµã³ã€ããŸãã
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 function)¶
A function or method which contains a yield expression (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 expression. 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 function)¶
async def ã䜿çšããŠå®çŸ©ããã颿°ãã¡ãœããã ã³ã«ãŒãã³é¢æ° (coroutine function) ãšåŒã³ãŸãã
åŒã³åºãããæããã®ãããªé¢æ°ã¯ coroutine ãªããžã§ã¯ããè¿ããŸãã
ã³ã«ãŒãã³é¢æ°ã¯ async with ã async for æã ãã§ãªã await åŒãæã€ããšãåºæ¥ãŸãã
ã³ã«ãŒãã³ãªããžã§ã¯ã ãåç
§ããŠãã ããã
3.2.8.5. éåæãžã§ãã¬ãŒã¿é¢æ° (asynchronous generator function)¶
A function or method which is defined using async def and
which contains a yield expression 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.
éåæã€ãã¬ãŒã¿ã® aiterator.__anext__ ã¡ãœãããåŒã³åºããšãä»ã®åŠçãåŸ
ããããŠãããšãã«ã yield åŒã䜿ãå€ãæäŸãããšãããŸã§åŠçãé²ãã awaitable ãè¿ããŸãã
ãã®é¢æ°ã空㮠return æãå®è¡ããããããã¯åŠçã®çµããã«å°éãããšãã¯ã StopAsyncIteration äŸå€ãéåºãããéåæã€ãã¬ãŒã¿ã¯åºåãã¹ãå€ã®æåŸã«å°éããããšã«ãªããŸãã
3.2.8.6. çµã¿èŸŒã¿é¢æ° (built-in function)¶
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 method)¶
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 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. ã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹Â¶
ä»»æã®ã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹ã¯ãã¯ã©ã¹ã§ __call__() ã¡ãœãããå®çŸ©ããããšã§åŒã³åºãå¯èœã«ãªããŸãã
3.2.9. ã¢ãžã¥ãŒã«Â¶
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 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 ãã¹ã¯ãªãã¿ (descriptor) ã®å®è£
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: |
|
ã¯ã©ã¹ãå®çŸ©ãããŠããã¢ãžã¥ãŒã«ã®ååã |
|
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 instance)¶
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 ãã¹ã¯ãªãã¿ (descriptor) ã®å®è£
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.
屿§ã®ä»£å
¥ãåé€ãè¡ããšãã€ã³ã¹ã¿ã³ã¹ã®èŸæžãæŽæ°ããŸãããã¯ã©ã¹ã®èŸæžãæŽæ°ããããšã¯ãããŸãããã¯ã©ã¹ã§ __setattr__() ã __delattr__() ã¡ãœãããå®çŸ©ãããŠããå ŽåãçŽæ¥ã€ã³ã¹ã¿ã³ã¹ã®èŸæžãæŽæ°ãã代ããã«ãããã®ã¡ãœãããåŒã³åºãããŸãã
ã¯ã©ã¹ã€ã³ã¹ã¿ã³ã¹ã¯ãããç¹å®ã®ååã®ã¡ãœãããæã£ãŠããå Žåãæ°å€åãã·ãŒã±ã³ã¹åããããã¯ãããåã®ããã«æ¯èãããšãã§ããŸãã ç¹æ®ã¡ãœããå ãåç §ããŠãã ããã
3.2.11.1. Special attributes¶
- object.__class__¶
ã¯ã©ã¹ã€ã³ã¹ã¿ã³ã¹ãå±ããŠããã¯ã©ã¹ã§ãã
3.2.12. I/O ãªããžã§ã¯ã (ãã¡ã€ã«ãªããžã§ã¯ãã®å¥å)¶
file object ã¯éããããã¡ã€ã«ã衚ããŸãããã¡ã€ã«ãªããžã§ã¯ããäœãããã®æ§ã
ãªã·ã§ãŒãã«ããããããŸã: 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 type)¶
ã€ã³ã¿ããªã¿ãå éšçã«äœ¿ã£ãŠããããã€ãã®åã¯ããŠãŒã¶ã«å ¬éãããŠããŸãããããã®å®çŸ©ã¯å°æ¥ã®ã€ã³ã¿ããªã¿ã®ããŒãžã§ã³ã§ã¯å€æŽãããå¯èœæ§ããããŸãããããã§ã¯èšè¿°ã®å®å šæ§ã®ããã«è§ŠããŠãããŸãã
3.2.13.1. ã³ãŒããªããžã§ã¯ã¶
ã³ãŒããªããžã§ã¯ã㯠ãã€ãã³ã³ãã€ã«ããã (byte-compiled) å®è¡å¯èœãª Python ã³ãŒããå¥å ãã€ãã³ãŒã ã衚çŸããŸããã³ãŒããªããžã§ã¯ããšé¢æ°ãªããžã§ã¯ãã®éãã¯ã颿°ãªããžã§ã¯ãã颿°ã®ã°ããŒãã«å€æ° (颿°ãå®çŸ©ããŠããã¢ãžã¥ãŒã«ã®ã°ããŒãã«) ã«å¯ŸããŠæç€ºçãªåç §ãæã£ãŠããã®ã«å¯Ÿããã³ãŒããªããžã§ã¯ãã«ã¯ã³ã³ããã¹ãããªããšããããšã§ã; ãŸãã颿°ãªããžã§ã¯ãã§ã¯ããã©ã«ãåŒæ°å€ãèšæ¶ã§ããŸãããã³ãŒããªããžã§ã¯ãã§ã¯ã§ããŸãã (å®è¡æã«èšç®ãããå€ã衚çŸãããã)ã颿°ãªããžã§ã¯ããšéããã³ãŒããªããžã§ã¯ãã¯å€æŽäžå¯èœã§ã倿Žå¯èœãªãªããžã§ã¯ããžã®åç §ã (çŽæ¥ã鿥ã«é¢ããã) å«ã¿ãŸããã
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. |
|
A Added in version 3.10. |
|
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 Code Objects Bit Flags 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) ãªããžã§ã¯ã¶
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) ãªããžã§ã¯ã¶
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) ãªããžã§ã¯ã¶
ã¹ã©ã€ã¹ãªããžã§ã¯ãã¯ã __getitem__() ã¡ãœããã®ããã®ã¹ã©ã€ã¹ã衚ãã®ã«äœ¿ãããŸããã¹ã©ã€ã¹ãªããžã§ã¯ãã¯çµã¿èŸŒã¿ã® slice() 颿°ã§ãçæãããŸãã
èªã¿åºãå°çšã®ç¹æ®å±æ§: start ã¯äžéã§ã; stop ã¯äžéã§ã; step ã¯ã¹ãããã®å€ã§ã; ããããçç¥ãããå Žå㯠None ãšãªã£ãŠããŸãããããã®å±æ§ã¯ä»»æã®åãæãŠãŸãã
ã¹ã©ã€ã¹ãªããžã§ã¯ãã¯ã¡ãœãããäžã€ãµããŒãããŸã:
- slice.indices(self, length)¶
ãã®ã¡ãœããã¯åäžã®æŽæ°åŒæ° length ãåããã¹ã©ã€ã¹ãªããžã§ã¯ãã length èŠçŽ ã®ã·ãŒã±ã³ã¹ã«é©çšããããšãã«è¡šçŸãããã¹ã©ã€ã¹ã«é¢ããæ å ±ãèšç®ããŸãããã®ã¡ãœãã㯠3 ã€ã®æŽæ°ãããªãã¿ãã«ãè¿ããŸã; ãããã start ããã³ stop ã®ã€ã³ããã¯ã¹ãšãstep ããªãã¡ã¹ã©ã€ã¹ã®ãŸããå¹ ã§ããã€ã³ããã¯ã¹å€ããªãããç¯å²å€ã®å€ã§ããã°ãéåžžã®ã¹ã©ã€ã¹ãšå€ãããªãããããã§æ±ãããŸãã
3.2.13.5. éçã¡ãœãã (static method) ãªããžã§ã¯ã¶
éçã¡ãœããã¯ãäžã§èª¬æãããããªé¢æ°ãªããžã§ã¯ãããã¡ãœãããªããžã§ã¯ããžã®å€æã黿¢ããããã®æ¹æ³ãæäŸããŸããéçã¡ãœãããªããžã§ã¯ãã¯ä»ã®äœããã®ãªããžã§ã¯ããéåžžã¯ãŠãŒã¶å®çŸ©ã¡ãœãããªããžã§ã¯ããå
ãã©ããã§ããéçã¡ãœãããã¯ã©ã¹ãã¯ã©ã¹ã€ã³ã¹ã¿ã³ã¹ããååŸãããšãå®éã«è¿ããããªããžã§ã¯ãã¯ã©ããããããªããžã§ã¯ãã«ãªãããã以äžã¯å€æã®å¯Ÿè±¡ã«ã¯ãªããŸãããéçã¡ãœãããªããžã§ã¯ãã¯éåžžåŒã³åºãå¯èœãªãªããžã§ã¯ããã©ããããŸãããéçãªããžã§ã¯ãèªäœã¯åŒã³åºãå¯èœã§ããéçãªããžã§ã¯ãã¯çµã¿èŸŒã¿ã³ã³ã¹ãã©ã¯ã¿ staticmethod() ã§çæãããŸãã
3.2.13.6. ã¯ã©ã¹ã¡ãœãããªããžã§ã¯ã¶
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. ç¹æ®ã¡ãœããå¶
ã¯ã©ã¹ã¯ãç¹æ®ãªååã®ã¡ãœãããå®çŸ©ããŠãç¹æ®ãªæ§æ (ç®è¡æŒç®ãæ·»ãå衚èšãã¹ã©ã€ã¹è¡šèšãªã©) ã«ããç¹å®ã®æŒç®ãå®è£
ã§ããŸããããã¯ãPython ã®æŒç®åãªãŒãããŒã (operator overloading) ãžã®ã¢ãããŒãã§ããããã«ãããã¯ã©ã¹ã¯èšèªã®æŒç®åã«å¯Ÿããç¬èªã®æ¯ãèããå®çŸ©ã§ããŸããäŸãã°ãããã¯ã©ã¹ã __getitem__() ãšããååã®ã¡ãœãããå®çŸ©ããŠããã x ããã®ã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹ã§ãããšãããšã x[i] 㯠type(x).__getitem__(x, i) ãšã»ãŒç䟡ã§ããç¹ã«æ³šéã®ãªãéããé©åãªã¡ãœãããå®çŸ©ãããŠããªããšãããã®ãããªæŒç®ã詊ã¿ããšäŸå€ (ãããŠã㯠AttributeError ã TypeError) ãéåºãããŸãã
ç¹æ®ã¡ãœããã« None ãèšå®ããããšã¯ãããã«å¯Ÿå¿ããæŒç®ãå©çšã§ããªãããšãæå³ããŸãã
äŸãã°ãã¯ã©ã¹ã® __iter__() ã None ã«èšå®ããå Žåããã®ã¯ã©ã¹ã¯ã€ãã©ãã«ã«ã¯ãªããããã®ã€ã³ã¹ã¿ã³ã¹ã«å¯Ÿã iter() ãåŒã³åºããš (__getitem__() ã«åŠçãæ»ãããã«) TypeError ãéåºããŸãã [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 ã®ã€ã³ã¹ã¿ã³ã¹) ã§ãªããã°ãªããŸãããå žåçãªå®è£ ã§ã¯ãã¯ã©ã¹ã®æ°ããªã€ã³ã¹ã¿ã³ã¹ãçæãããšãã«ã¯
super().__new__(cls[, ...])ã«é©åãªåŒæ°ãæå®ããŠã¹ãŒãã¯ã©ã¹ã®__new__()ã¡ãœãããåŒã³åºããæ°ãã«çæãããã€ã³ã¹ã¿ã³ã¹ã«å¿ èŠãªå€æŽãå ããŠããè¿ããŸãããã
__new__()ã ãªããžã§ã¯ãã®äœæäžã«åŒã³åºãããcls ã®ã€ã³ã¹ã¿ã³ã¹ãè¿ããå Žåã«ã¯ã__init__(self[, ...])ã®ããã«ããŠæ°ããã€ã³ã¹ã¿ã³ã¹ã®__init__()ãåŒã³åºãããŸãããã®ãšãã self ã¯æ°ãã«çæãããã€ã³ã¹ã¿ã³ã¹ã§ãæ®ãã®åŒæ°ã¯ãªããžã§ã¯ãã³ã³ã¹ãã©ã¯ã¿ã«æž¡ãããåŒæ°ãšåãã«ãªããŸãã__new__()ã cls ã®ã€ã³ã¹ã¿ã³ã¹ãè¿ããªãå Žåãã€ã³ã¹ã¿ã³ã¹ã®__init__()ã¡ãœããã¯åŒã³åºãããŸããã__new__()ã®äž»ãªç®çã¯ã倿Žäžèœãªå (int, str, tuple ãªã©) ã®ãµãã¯ã©ã¹ã§ã€ã³ã¹ã¿ã³ã¹çæãã«ã¹ã¿ãã€ãºããããšã«ãããŸãããŸããã¯ã©ã¹çæãã«ã¹ã¿ãã€ãºããããã«ãã«ã¹ã¿ã ã®ã¡ã¿ã¯ã©ã¹ã§ãããªãŒããŒã©ã€ããããŸãã
- object.__init__(self[, ...])¶
ã€ã³ã¹ã¿ã³ã¹ã (
__new__()ã«ãã£ãŠ) çæãããåŸããããåŒã³åºãå ã«è¿ãããåã«åŒã³åºãããŸããåŒæ°ã¯ã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿åŒã«æž¡ãããã®ã§ããåºåºã¯ã©ã¹ãšãã®æŽŸçã¯ã©ã¹ããšãã«__init__()ã¡ãœãããæã€å ŽåãæŽŸçã¯ã©ã¹ã®__init__()ã¡ãœããã¯åºåºã¯ã©ã¹ã®__init__()ã¡ãœãããæç€ºçã«åŒã³åºããŠãã€ã³ã¹ã¿ã³ã¹ã®åºåºã¯ã©ã¹éšåãé©åã«åæåãããããšä¿èšŒããªããã°ãªããŸãããäŸãã°ãsuper().__init__([args...])ã__new__()ãš__init__()ã¯é£æºããŠãªããžã§ã¯ããæ§æãã (__new__()ãäœæãã__init__()ããããã«ã¹ã¿ãã€ãºãã) ã®ã§ã__init__()ããéNoneå€ãè¿ããŠã¯ãããŸãã; ããããŠããŸããšãå®è¡æã«TypeErrorãéåºãããŠããŸããŸãã
- object.__del__(self)¶
ã€ã³ã¹ã¿ã³ã¹ãç Žæ£ããããšãã«åŒã³åºãããŸãã ããã¯ãã¡ã€ãã©ã€ã¶ã (é©åã§ã¯ãããŸããã) ãã¹ãã©ã¯ã¿ãšãåŒã°ããŸãã åºåºã¯ã©ã¹ã
__del__()ã¡ãœãããæã£ãŠããå Žåã¯ã掟çã¯ã©ã¹ã®__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ã®åç §ã«ãŠã³ãã 1 ã€æžãããåŸè ã¯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ã«èšå®ãããŠãããããããŸããã Python ã¯ãåäžã®ã¢ã³ããŒã¹ã³ã¢ã§å§ãŸãååã®ã°ããŒãã«ãªããžã§ã¯ãã¯ãä»ã®ã°ããŒãã«å€æ°ãåé€ãããåã«ã¢ãžã¥ãŒã«ããåé€ãããããšãä¿èšŒããŸã; ãã®ãããªã°ããŒãã«å€æ°ãžã®ä»ããã®åç §ãååšããªãå Žåã__del__()ã¡ãœãããåŒã°ããæç¹ã§ãã€ã³ããŒããããã¢ãžã¥ãŒã«ããŸã å©çšå¯èœã§ããããšãä¿èšŒããã®ã«åœ¹ç«ã€ãããããŸããã
- object.__repr__(self)¶
repr()çµã¿èŸŒã¿é¢æ°ã«ãã£ãŠåŒã³åºããããªããžã§ã¯ãã衚ããå ¬åŒã® (official)ãæååãèšç®ããŸããå¯èœãªãããã㯠(é©åãªç°å¢ãäžããããã°) åãå€ã®ãªããžã§ã¯ããåçæããã®ã«äœ¿ãããæå¹ãª Python åŒã®ãããªãã®ã§ããã¹ãã§ããã§ããªããªãã<...some useful description...>圢åŒã®æååãè¿ãããã¹ãã§ããæ»ãå€ã¯æååãªããžã§ã¯ãã§ãªããã°ãªããŸãããã¯ã©ã¹ã__repr__()ãå®çŸ©ããŠããŠ__str__()ã¯å®çŸ©ããŠããªããã°ããã®ã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹ã®ãéå ¬åŒã® (informal)ãæåå衚çŸãèŠæ±ããããšãã«ã__repr__()ã䜿ãããŸãã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__()ãæå¹ãª Python 衚çŸãè¿ãããšãæåŸ ãããªããšããç¹ã§ããã®ã¡ãœããã¯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()çµã¿èŸŒã¿é¢æ°ãããã«ã¯ ãã©ãŒãããæžã¿æååãªãã©ã« ã®è©äŸ¡ãstr.format()ã¡ãœããã«ãã£ãŠåŒã³åºããããªããžã§ã¯ãã® "ãã©ãŒãããåããã (formatted)" æåå衚çŸãäœããŸãã 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, see@functools.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ã®ãµã€ãºã«åãè©°ããŸãã ãã㯠64-bit ã§ãã«ããããŠãããš 8 ãã€ãã§ã 32-bit ã§ãã«ããããŠãããš 4 ãã€ãã§ãã ãªããžã§ã¯ãã®__hash__()ãç°ãªã bit ãµã€ãºã®ãã«ãã§ã坿¬æ§ãå¿ èŠã§ããå Žåã¯ãå¿ ãå šãŠã®ãµããŒããããã«ãã® bit å¹ ããã§ãã¯ããŠãã ããã ããããç°¡åãªæ¹æ³ã¯python -c "import sys; print(sys.hash_info.width)"ãå®è¡ããããšã§ããã¯ã©ã¹ã
__eq__()ã¡ãœãããå®çŸ©ããŠããªããªãã__hash__()ã¡ãœãããå®çŸ©ããŠã¯ãªããŸãã; ã¯ã©ã¹ã__eq__()ãå®çŸ©ããŠããŠã__hash__()ãå®çŸ©ããŠããªããªãããã®ã€ã³ã¹ã¿ã³ã¹ã¯ããã·ã¥å¯èœã³ã¬ã¯ã·ã§ã³ã®èŠçŽ ãšããŠäœ¿ããŸãããã¯ã©ã¹ããã¥ãŒã¿ãã«ãªãªããžã§ã¯ããå®çŸ©ããŠããã__eq__()ã¡ãœãããå®è£ ããŠãããªãã__hash__()ãå®çŸ©ããŠã¯ãªããŸãããããã¯ãããã·ã¥å¯èœ ã³ã¬ã¯ã·ã§ã³ã®å®è£ ã«ãããŠããŒã®ããã·ã¥å€ãã€ãã¥ãŒã¿ãã«ã§ããããšãèŠæ±ãããŠããããã§ã (ãªããžã§ã¯ãã®ããã·ã¥å€ãå€åãããšã誀ã£ãããã·ã¥ãã±ã: 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ãå«ããŠãã ãããã¯ã©ã¹èªèº«ã§æç€ºçã«TypeErrorãéåºãã__hash__()ãå®çŸ©ãããšãisinstance(obj, collections.abc.Hashable)åŒã³åºãã§èª€ã£ãŠããã·ã¥å¯èœãšèå¥ãããã§ããããæ³šé
ããã©ã«ãã§ã¯ãæååãšãã€ãåã®
__hash__()å€ã¯äºæž¬äžå¯èœãªã©ã³ãã å€ã§ "ãœã«ã" ãããŸãã ããã·ã¥å€ã¯åç¬ã® Python ããã»ã¹å ã§ã¯å®æ°ã§ããç¶ããŸãããPython ãç¹°ãè¿ãèµ·åããæ¯ã«ãäºæž¬ã§ããªããªããŸãã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.
ããã·ã¥å€ã®å€æŽã¯ãéåã®ã€ãã¬ãŒã·ã§ã³é åºã«åœ±é¿ããŸããPython ã¯ãã®é åºä»ããä¿èšŒããŠããŸãã (ãããŠéåžž 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 ã®äœ¿çšã x.name ãžã®ä»£å
¥ã 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__()ãå®çŸ©ããŠããå Žåã__getattr__()ã¯ã__getattribute__()ã§æç€ºçã«åŒã³åºãããAttributeErroräŸå€ãéåºããªãéãåŒã°ããŸããããã®ã¡ãœãã㯠(èšç®ããã) 屿§å€ãè¿ãããAttributeErroräŸå€ãéåºããŸãããã®ã¡ãœãããååž°çã«ééãªãåŒã³åºãããŠããŸãã®ãé²ããããå®è£ ã®éã«ã¯åžžã«ãå¿ èŠãªå±æ§å šãŠãžã®ã¢ã¯ã»ã¹ã§ãäŸãã°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.__getattr__ã䜿ã£ã屿§ã®åé€ã¯ ç£æ»ã€ãã³ã ãéåºããŸãã
- 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__ 颿°ã¯å±æ§åã§ãã 1 åŒæ°ãåãåããèšç®ããå€ãè¿ãã 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__ ãèšå®ãããããŠãã圱é¿ãããã®ã¯å±æ§ã¢ã¯ã»ã¹ã®æ§æã䜿ãããæ€çŽ¢ã ãã§ã -- ã¢ãžã¥ãŒã«ã® globals ãžã®çŽæ¥ã¢ã¯ã»ã¹ã¯ (ã¢ãžã¥ãŒã«å
ã®ã³ãŒããããšã¢ãžã¥ãŒã«ã® globals ã®ã©ã¡ãã§ã) 圱é¿ãåããŸããã
ããŒãžã§ã³ 3.5 ã§å€æŽ: ã¢ãžã¥ãŒã«ã®å±æ§ __class__ ãæžã蟌ã¿å¯èœã«ãªããŸããã
Added in version 3.7: __getattr__ ã¢ãžã¥ãŒã«å±æ§ãš __dir__ ã¢ãžã¥ãŒã«å±æ§ã
åè
- PEP 562 - ã¢ãžã¥ãŒã«ã® __getattr__ ãš __dir__
ã¢ãžã¥ãŒã«ã®
__getattr__颿°ããã³__dir__颿°ã®èª¬æã
3.3.2.2. ãã¹ã¯ãªãã¿ (descriptor) ã®å®è£ ¶
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)¶
ãªãŒããŒã¯ã©ã¹ïŒã¯ã©ã¹å±æ§ã¢ã¯ã»ã¹ã®å ŽåïŒããã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹ïŒã€ã³ã¹ã¿ã³ã¹å±æ§ã¢ã¯ã»ã¹ã®å ŽåïŒã®å±æ§ååŸæã«åŒã³åºãããŸãã instance ãéããŠå±æ§ãã¢ã¯ã»ã¹ããæã«ããªãã·ã§ã³ã® owner åŒæ°ã¯ãªãŒããŒã¯ã©ã¹ã§ãã owner ãéããŠå±æ§ã¢ã¯ã»ã¹ãããšãã¯
Noneã§ãããã®ã¡ãœããã¯ãç®åºããã屿§å€ãè¿ããã
AttributeErroräŸå€ãéåºããŸããPEP 252 ã¯
__get__()ã¯1ã€ã2ã€ã®åŒæ°ãæã€åŒã³åºãå¯èœãªããžã§ã¯ãã§ãããšå®çŸ©ããŠããŸããPythonã®çµã¿èŸŒã¿ã®ãã¹ã¯ãªãã¿ã¯ãã®ä»æ§ããµããŒãããŠããŸããããµãŒãããŒãã£è£œã®ããŒã«ã®äžã«ã¯äž¡æ¹ã®åŒæ°ãå¿ èŠãšãããã®ããããŸããPythonã®__getattribute__()å®è£ ã¯å¿ èŠãã©ããã«é¢ããããäž¡æ¹ã®åŒæ°ãåžžã«æž¡ããŸãã
- object.__set__(self, instance, value)¶
ãªãŒããŒã¯ã©ã¹ã®ã€ã³ã¹ã¿ã³ã¹ instance äžã®å±æ§ãæ°ããªå€ value ã«èšå®ããéã«åŒã³åºãããŸãã
__set__()ãããã¯__delete__()ã远å ãããšããã¹ã¯ãªãã¿ã¯ãããŒã¿ãã¹ã¯ãªãã¿ãã«å€ãããŸãã詳现㯠ãã¹ã¯ãªãã¿ã®åŒã³åºã ãåç §ããŠãã ããã
- 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. ãã¹ã¯ãªãã¿ã®åŒã³åºã¶
äžè¬ã«ãã¹ã¯ãªãã¿ãšã¯ãç¹æ®ãª "æçžã«é¢ããåäœ (binding behaviour)" ããã€ãªããžã§ã¯ã屿§ã®ããšã§ãããã¹ã¯ãªãã¿ã¯ããã¹ã¯ãªãã¿ãããã³ã« (descriptor protocol) ã®ã¡ãœãã: __get__(), __set__(), ããã³ __delete__() ã䜿ã£ãŠã屿§ã¢ã¯ã»ã¹ããªãŒããŒã©ã€ãããŠãããã®ã§ãããããã®ã¡ãœããã®ããããããªããžã§ã¯ãã«å¯ŸããŠå®çŸ©ãããŠããå Žåããªããžã§ã¯ãã¯ãã¹ã¯ãªãã¿ã§ãããšãããŸãã
屿§ã¢ã¯ã»ã¹ã®ããã©ã«ãã®åäœã¯ããªããžã§ã¯ãã®èŸæžããå€ãåãåºããããå€ãèšå®ããããåé€ããããããšãããã®ã§ããäŸãã°ã a.x ã«ãã屿§ã®æ€çŽ¢ã§ã¯ããŸã a.__dict__['x'] ãæ¬¡ã« type(a).__dict__['x'] ããã㊠type(a) ã®åºåºã¯ã©ã¹ã§ã¡ã¿ã¯ã©ã¹ã§ãªããã®ã«ç¶ãããšãã£ãå
·åã«é£éãèµ·ãããŸãã
ããããæ€çŽ¢å¯Ÿè±¡ã®å€ãããã¹ã¯ãªãã¿ã¡ãœããã®ãããããå®çŸ©ããŠãããªããžã§ã¯ãã§ããã°ãPython ã¯ããã©ã«ãã®åäœããªãŒããŒã©ã€ãããŠã代ããã«ãã¹ã¯ãªãã¿ã¡ãœãããåŒã³åºããŸããå è¿°ã®é£éã®äžã®ã©ãã§ãã¹ã¯ãªãã¿ã¡ãœãããåŒã³åºããããã¯ãã©ã®ãã¹ã¯ãªãã¿ã¡ãœãããå®çŸ©ãããŠããŠãã©ã®ããã«åŒã³åºããããã«äŸåããŸãã
ãã¹ã¯ãªãã¿åŒã³åºãã®åºç¹ãšãªãã®ã¯ã屿§åãžã®æçž (binding) ãããªãã¡ a.x ã§ããåŒæ°ãã©ã®ããã«ãã¹ã¯ãªãã¿ã«çµåãããã㯠a ã«äŸåããŸã:
- çŽæ¥åŒã³åºã (Direct Call)
æãåçŽã§ããã€ãã£ãã«äœ¿ãããªãåŒã³åºãæäœã¯ãã³ãŒãäžã§çŽæ¥ãã¹ã¯ãªãã¿ã¡ãœããã®åŒã³åºã:
x.__get__(a)ãè¡ããšãããã®ã§ãã- ã€ã³ã¹ã¿ã³ã¹æçž (Instance Binding)
ãªããžã§ã¯ãã€ã³ã¹ã¿ã³ã¹ãžæçžãããšã
a.xã¯åŒã³åºãtype(a).__dict__['x'].__get__(a, type(a))ã«å€æãããŸãã- ã¯ã©ã¹æçž (Class Binding)
ã¯ã©ã¹ãžæçžãããšã
A.xã¯åŒã³åºãA.__dict__['x'].__get__(None, A)ã«å€æãããŸãã- super æçž (Super Binding)
super(A, a).xã®ãããªãããã䜿ã£ãã«ãã¯ã¢ããã¯a.__class__.__mro__ãæ¢çŽ¢ããŠãAã®åã®ã¯ã©ã¹BããŸãæ¢ããB.__dict__['x'].__get__(a, A)ãè¿ããŸãããããã¹ã¯ãªãã¿ã§ãªããã°xã倿Žããã«è¿ããŸãã
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.
The @property decorator is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.
3.3.2.4. __slots__¶
__slots__ ã䜿ããšã(ããããã£ã®ããã«) ããŒã¿ã¡ã³ããæç€ºçã«å®£èšãã (æç€ºçã« __slots__ ã§å®£èšããŠããã芪ã¯ã©ã¹ã«ååšããŠãããã§ãªãéã) __dict__ ã __weakref__ ãäœæããªãããã«ã§ããŸãã
__dict__ ã䜿ãã®ã«æ¯ã¹ãŠãç¯çŽã§ããã¡ã¢ãªç©ºéã¯ããªã倧ããã§ãã
屿§æ¢çŽ¢ã®ã¹ããŒããããªãåäžã§ããŸãã
- object.__slots__¶
ãã®ã¯ã©ã¹å€æ°ã«ã¯ãã€ã³ã¹ã¿ã³ã¹ãçšãã倿°åã衚ããæååãã€ãã©ãã«ããŸãã¯æååã®ã·ãŒã±ã³ã¹ãä»£å ¥ã§ããŸãã__slots__ ã¯ãåã€ã³ã¹ã¿ã³ã¹ã«å¯ŸããŠå®£èšããã倿°ã«å¿ èŠãªèšæ¶é åã確ä¿ãã
__dict__ãš __weakref__ ãèªåçã«çæãããªãããã«ããŸãã
Notes on using __slots__:
__slots__ ãæããªãã¯ã©ã¹ããç¶æ¿ãããšããã€ã³ã¹ã¿ã³ã¹ã®
__dict__屿§ãš __weakref__ 屿§ã¯åžžã«å©çšå¯èœã§ãã__dict__倿°ããªãå Žåã __slots__ ã«åæãããŠããªãæ°ããªå€æ°ãã€ã³ã¹ã¿ã³ã¹ã«ä»£å ¥ããããšã¯ã§ããŸãããåæãããŠããªã倿°åã䜿ã£ãŠä»£å ¥ããããšããå ŽåãAttributeErrorãéåºãããŸããæ°ããªå€æ°ãåçã«ä»£å ¥ãããã®ãªãã __slots__ ã宣èšããéã«'__dict__'ã倿°åã®ã·ãŒã±ã³ã¹ã«è¿œå ããŠãã ããã__slots__ ãå®çŸ©ããŠããã¯ã©ã¹ã®åã€ã³ã¹ã¿ã³ã¹ã« __weakref__ 倿°ããªãå Žåãã€ã³ã¹ã¿ã³ã¹ã«å¯Ÿãã匱åç § (
weak references) ã¯ãµããŒããããŸããã匱åç §ã®ãµããŒããå¿ èŠãªãã __slots__ ã宣èšããéã«'__weakref__'ã倿°åã®ã·ãŒã±ã³ã¹ã«è¿œå ããŠãã ããã__slots__ ã¯ãã¯ã©ã¹ã®ã¬ãã«ã§å倿°ã«å¯Ÿãã ãã¹ã¯ãªãã¿ ã䜿ã£ãŠå®è£ ãããŸãããã®çµæã __slots__ ã«å®çŸ©ãããŠããã€ã³ã¹ã¿ã³ã¹å€æ°ã®ããã©ã«ãå€ã¯ã¯ã©ã¹å±æ§ã䜿ã£ãŠèšå®ã§ããªããªã£ãŠããŸã; ããããªããšããã¹ã¯ãªãã¿ã«ããä»£å ¥ãã¯ã©ã¹å±æ§ãäžæžãããŠããŸãããã§ãã
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).ããã¯ã©ã¹ã§ãåºåºã¯ã©ã¹ã§ãã§ã«å®çŸ©ãããŠããã¹ããããå®çŸ©ããå Žåãåºåºã¯ã©ã¹ã®ã¹ãããã§å®çŸ©ãããŠããã€ã³ã¹ã¿ã³ã¹å€æ°ã¯ (ãã¹ã¯ãªãã¿ãåºåºã¯ã©ã¹ããçŽæ¥ååŸããªãéã) ã¢ã¯ã»ã¹ã§ããªããªããŸããããã«ãããããã°ã©ã ã®è¶£æãäžå®ã«ãªã£ãŠããŸããŸããå°æ¥ã¯ããã®åé¡ãé¿ããããã«äœããã®ãã§ãã¯ã远å ããããããããŸããã
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.ãã __slots__ ã«å¯Ÿã㊠ã€ãã¬ãŒã¿ ã䜿çšãããšãã€ãã¬ãŒã¿ã®å€ããšã« ãã¹ã¯ãªãã¿ ãäœãããŸãããããã __slots__ 屿§ã¯ç©ºã®ã€ãã¬ãŒã¿ãšãªããŸãã
3.3.3. ã¯ã©ã¹çæãã«ã¹ã¿ãã€ãºãã¶
ã¯ã©ã¹ãä»ã®ã¯ã©ã¹ãç¶æ¿ãããšãã«å¿
ãã芪ã¯ã©ã¹ã® __init_subclass__() ãåŒã³åºãããŸãããããå©çšãããšããµãã¯ã©ã¹ã®æåã倿Žããã¯ã©ã¹ãæžãããšãã§ããŸããããã¯ãã¯ã©ã¹ãã³ã¬ãŒã¿ãšãšãŠãè¯ã䌌ãŠããŸãããã¯ã©ã¹ãã³ã¬ãŒã¿ãããããé©çšãããç¹å®ã®ã¯ã©ã¹ã«ã®ã¿ã«åœ±é¿ããã®ã«å¯ŸããŠã __init_subclass__ ã¯ããã£ã±ãããã®ã¡ãœãããå®çŸ©ããã¯ã©ã¹ã®å°æ¥ã®ãµãã¯ã©ã¹ã«é©çšãããŸãã
- 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)¶
ãªãŒããŒãšãªãã¯ã©ã¹ owner ãäœæãããæç¹ã§èªåçã«åŒã³åºãããŸãã ãªããžã§ã¯ãã¯ãã®ã¯ã©ã¹ã® name ã«å²ãåœãŠãããŸãã
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()ã®ã€ã³ã¹ã¿ã³ã¹ãäžããããããåºåºãå®çŸ©ãããŠããå Žåã¯ãæã掟çãã (ç¶æ¿é¢ä¿ã§æãäžã®) ã¡ã¿ã¯ã©ã¹ã䜿ãããŸãã
æã掟ççãªã¡ã¿ã¯ã©ã¹ã¯ã(ããããã°) æç€ºçã«æå®ãããã¡ã¿ã¯ã©ã¹ãšãæå®ããããã¹ãŠã®ããŒã¹ã¯ã©ã¹ã®ã¡ã¿ã¯ã©ã¹ããéžã°ããŸããæã掟ççãªã¡ã¿ã¯ã©ã¹ã¯ããããã®ã¡ã¿ã¯ã©ã¹åè£ã®ãã¹ãŠã®ãµãã¿ã€ãã§ãããããªãã®ã§ããã¡ã¿ã¯ã©ã¹åè£ã®ã©ãããã®åºæºãæºãããªããã°ãã¯ã©ã¹å®çŸ©ã¯ TypeError ã§å€±æããŸãã
3.3.3.4. ã¯ã©ã¹ã®åå空éã®æºå¶
é©åãªã¡ã¿ã¯ã©ã¹ãæå®ããããšãã¯ã©ã¹ã®åå空éãçšæãããŸããããã¡ã¿ã¯ã©ã¹ã __prepare__ 屿§ãæã£ãŠããå Žåã namespace = metaclass.__prepare__(name, bases, **kwds) ãåŒã°ããŸãã远å ã®ããŒã¯ãŒãåŒæ°ã¯ãããã¯ã©ã¹å®çŸ©ã«ããã°èšå®ãããŸãã __prepare__ ã¡ãœãã㯠ã¯ã©ã¹ã¡ãœãã ãšããŠå®è£
ããå¿
èŠããããŸãã __prepare__ ãäœæããŠè¿ããåå空é㯠__new__ ã«æž¡ãããŸãããæçµçãªã¯ã©ã¹ãªããžã§ã¯ãã¯æ°ãã dict ã«ã³ããŒããŠäœæãããŸãã
ã¡ã¿ã¯ã©ã¹ã« __prepare__ 屿§ããªãå Žåãã¯ã©ã¹ã®åå空éã¯ç©ºã® é åºä»ããããã³ã°ãšããŠåæåãããŸãã
åè
- PEP 3115 - Metaclasses in Python 3000
__prepare__åå空éããã¯ã®å°å ¥
3.3.3.5. ã¯ã©ã¹æ¬äœã®å®è¡Â¶
ã¯ã©ã¹æ¬äœã (倧ãŸãã«ã¯) exec(body, globals(), namespace) ãšããŠå®è¡ãããŸããéåžžã®åŒã³åºããš exec() ã®éèŠãªéãã¯ãã¯ã©ã¹å®çŸ©ã颿°å
éšã§è¡ãããå Žåãã¬ãã·ã«ã«ã¹ã³ãŒãã«ãã£ãŠã¯ã©ã¹æ¬äœ (ä»»æã®ã¡ãœãããå«ã) ãçŸåšã®ã¹ã³ãŒããšå€åŽã®ã¹ã³ãŒãããååãåç
§ã§ãããšããç¹ã§ãã
ããããã¯ã©ã¹å®çŸ©ã颿°å
éšã§è¡ãããæã§ãããã¯ã©ã¹å
éšã§å®çŸ©ãããã¡ãœããã¯ã¯ã©ã¹ã¹ã³ãŒãã§å®çŸ©ãããååãèŠãããšã¯ã§ããŸãããã¯ã©ã¹å€æ°ã¯ã€ã³ã¹ã¿ã³ã¹ã¡ãœãããã¯ã©ã¹ã¡ãœããã®æåã®ãã©ã¡ãŒã¿ããã¢ã¯ã»ã¹ããããæ¬¡ã®ç¯ã§èª¬æãããæé»çã«éçã¹ã³ãŒããåãããŠãã __class__ åç
§ããã¢ã¯ã»ã¹ããªããã°ãªããŸããã
3.3.3.6. ã¯ã©ã¹ãªããžã§ã¯ãã®äœæÂ¶
ã¯ã©ã¹æ¬äœã®å®è¡ã«ãã£ãŠã¯ã©ã¹ã®åå空éãåæåãããããmetaclass(name, bases, namespace, **kwds) ãåŒã³åºãããšã§ã¯ã©ã¹ãªããžã§ã¯ããäœæãããŸã (ããã§æž¡ããã远å ã®ããŒã¯ãŒã㯠__prepare__ ã«æž¡ããããã®ãšåãã§ã)ã
ãã®ã¯ã©ã¹ãªããžã§ã¯ãã¯ã super() ã®ç¡åŒæ°åœ¢åŒã«ãã£ãŠåç
§ããããã®ã§ãã __class__ ã¯ãã¯ã©ã¹æ¬äœäžã®ã¡ãœããã __class__ ãŸã㯠super ã®ãããããåç
§ããŠããå Žåã«ãã³ã³ãã€ã©ã«ãã£ãŠäœæãããæé»ã®ã¯ããŒãžã£ãŒåç
§ã§ããããã¯ãã¡ãœããã«æž¡ãããæåã®åŒæ°ã«åºã¥ããŠçŸåšã®åŒã³åºããè¡ãããã«äœ¿çšãããã¯ã©ã¹ãŸãã¯ã€ã³ã¹ã¿ã³ã¹ãèå¥ãããäžæ¹ã super() ã®ç¡åŒæ°åœ¢åŒãã¬ãã·ã«ã«ã¹ã³ãŒãã«åºã¥ããŠå®çŸ©ãããŠããã¯ã©ã¹ãæ£ç¢ºã«èå¥ããããšãå¯èœã«ããŸãã
CPython 3.6 以éã§ã¯ã __class__ ã»ã«ã¯ãã¯ã©ã¹åå空éã«ãã __classcell__ ãšã³ããªãŒãšããŠã¡ã¿ã¯ã©ã¹ã«æž¡ãããŸãã
__class__ ã»ã«ãååšããŠããå Žåã¯ããã®ã¯ã©ã¹ãæ£ããåæåãããããã«ã type.__new__ ã®åŒã³åºãã«å°éãããŸã§äžã«äŒæ¬ãããŸãã
倱æããå Žåã¯ãPython 3.8 ã§ã¯ RuntimeError ã«ãªããŸãã
ããã©ã«ãã®ã¡ã¿ã¯ã©ã¹ type ãæçµçã«ã¯ type.__new__ ãåŒã³åºãã¡ã¿ã¯ã©ã¹ã䜿ã£ãŠãããšãã¯ãã¯ã©ã¹ãªããžã§ã¯ããäœæããåŸã«æ¬¡ã®ã«ã¹ã¿ã åã®æé ãèµ·åãããŸã:
type.__new__ã¡ãœããã__set_name__()ãå®çŸ©ãããŠããã¯ã©ã¹ã®åå空éã«ããå šãŠã®å±æ§ãåéããŸã;ãããã®
__set_name__ã¡ãœãããããã®ã¡ãœãããå®çŸ©ãããŠããã¯ã©ã¹ãããã³ããã«å±ãã屿§ã«å²ãåœãŠãããŠããååãåŒæ°ãšããŠåŒã³åºãããŸã;æ°ããã¯ã©ã¹ã®ã¡ãœãã解決é åºã§ããäžã«äœçœ®ãã芪ã¯ã©ã¹ã§
__init_subclass__()ããã¯ãåŒã³åºãããŸãã
ã¯ã©ã¹ãªããžã§ã¯ããäœæãããåŸã«ã¯ãã¯ã©ã¹å®çŸ©ã«å«ãŸããŠããã¯ã©ã¹ãã³ã¬ãŒã¿ (ããããã°) ã«ã¯ã©ã¹ãªããžã§ã¯ããæž¡ããããã³ã¬ãŒã¿ãè¿ããªããžã§ã¯ããããã§å®çŸ©ãããã¯ã©ã¹ãšããŠããŒã«ã«ã®åå空éã«æçžãããŸãã
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 - New super
æé»ã®
__class__ã¯ããŒãžã£åç §ã«ã€ããŠèšè¿°ããŠããŸã
3.3.3.7. ã¡ã¿ã¯ã©ã¹ã®çšé¶
ã¡ã¿ã¯ã©ã¹ã¯éããªãæœåšçå©çšäŸ¡å€ãæã£ãŠããŸãããããŸã§è©ŠãããŠããã¢ã€ãã¢ã«ã¯ãåæåããã°èšé²ãã€ã³ã¿ãŒãã§ãŒã¹ã®ãã§ãã¯ã èªåããªã²ãŒã·ã§ã³ãèªåããããã£çæããããã·ããã¬ãŒã ã¯ãŒã¯ããããŠèªåãªãœãŒã¹ããã¯ïŒåæãšãã£ããã®ããããŸãã
3.3.4. ã€ã³ã¹ã¿ã³ã¹ã®ã«ã¹ã¿ãã€ãºãšãµãã¯ã©ã¹ãã§ãã¯Â¶
以äžã®ã¡ãœããã¯çµã¿èŸŒã¿é¢æ° isinstance() ãš issubclass() ã®ããã©ã«ãã®åäœãäžæžãããã®ã«å©çšããŸãã
ç¹ã«ã abc.ABCMeta ã¡ã¿ã¯ã©ã¹ã¯ãæœè±¡åºåºã¯ã©ã¹ (ABCs) ã"ä»®æ³åºåºã¯ã©ã¹ (virtual base classes)" ãšããŠãä»ã® ABC ãå«ããä»»æã®ã¯ã©ã¹ã (çµã¿èŸŒã¿åãå«ã) åã«è¿œå ããããã«ããããã®ã¡ãœãããå®è£
ããŠããŸãã
- type.__instancecheck__(self, instance)¶
instance ã (çŽæ¥ããŸãã¯éæ¥çã«) class ã®ã€ã³ã¹ã¿ã³ã¹ãšèããããå Žåã« true ãè¿ããŸããå®çŸ©ãããŠããã°ã
isinstance(instance, class)ã®å®è£ ã®ããã«åŒã³åºãããŸãã
- type.__subclasscheck__(self, subclass)¶
subclass ã (çŽæ¥ããŸãã¯éæ¥çã«) class ã®ãµãã¯ã©ã¹ãšèããããå Žåã« true ãè¿ããŸããå®çŸ©ãããŠããã°ã
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 - åãã³ã
Introducing Python's framework for type annotations
- Generic Alias Types
Documentation for objects representing parameterized generic classes
- ãžã§ããªã¯ã¹, user-defined generics and
typing.Generic å®è¡æã«ãã©ã¡ãŒã¿èšå®ãå¯èœã§ããããã€éçãªåãã§ãã«ãŒãçè§£ã§ãããžã§ããªãã¯ã¯ã©ã¹ãå®è£ ããæ¹æ³ã®ããã¥ã¡ã³ãã§ãã
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 - typing ã¢ãžã¥ãŒã«ãšãžã§ããªãã¯åã«å¯Ÿããèšèªã³ã¢ã«ãããµããŒã
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)¶
self[key]ã®å®è£ ã«ãããŠèŸæžå ã«ããŒãååšããªãã£ãå Žåã«ã dict ã®ãµãã¯ã©ã¹ã®ããã«dict.__getitem__()ã«ãã£ãŠåŒã³åºãããŸãã
- object.__iter__(self)¶
ãã®ã¡ãœããã¯ãã³ã³ããã«å¯Ÿã㊠ã€ãã¬ãŒã¿ ãèŠæ±ãããéã«åŒã³åºãããŸãããã®ã¡ãœããã¯ãã³ã³ããå ã®å šãŠã®ãªããžã§ã¯ãã«æž¡ã£ãŠå埩åŠçã§ãããããªãæ°ããªã€ãã¬ãŒã¿ãªããžã§ã¯ããè¿ããªããã°ãªããŸããããããã³ã°ã§ã¯ãã³ã³ããå ã®ããŒã«æž¡ã£ãŠå埩åŠçããªããã°ãªããŸããã
- object.__reversed__(self)¶
reversed()çµã¿èŸŒã¿é¢æ°ãéæ¹åã€ãã¬ãŒã·ã§ã³ãå®è£ ããããã«ã(ååšããã°)åŒã³åºããŸããã³ã³ããå ã®å šèŠçŽ ãéé ã«ã€ãã¬ãŒããããæ°ããã€ãã¬ãŒã¿ãè¿ãã¹ãã§ãã__reversed__()ã¡ãœãããå®çŸ©ãããŠããªãå Žåãreversed()çµèŸŒã¿é¢æ°ã¯ sequence ãããã³ã« (__len__()ãš__getitem__()) ã䜿ã£ãæ¹æ³ã«ãã©ãŒã«ããã¯ããŸãã sequence ãããã³ã«ããµããŒããããªããžã§ã¯ãã¯ã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()ãå®è£ ããŸãã Python ãæ°å€ãªããžã§ã¯ããæŽæ°ãªããžã§ã¯ãã«æå€±ãªã倿ããå¿ èŠãããå Žå (ããšãã°ã¹ã©ã€ã·ã³ã°ããçµã¿èŸŒã¿ã®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 æã®å®è¡æã«ã©ã³ã¿ã€ã ã³ã³ããã¹ããå®çŸ©ãããªããžã§ã¯ãã§ããã³ã³ããã¹ããããŒãžã£ã¯ãã³ãŒããããã¯ãå®è¡ããããã«å¿
èŠãªå
¥ãå£ããã³åºå£ã®åŠçãæ±ããŸããã³ã³ããã¹ããããŒãžã£ã¯éåžžã with æïŒ with æ ã®ç« ãåç
§ïŒã«ããèµ·åãããŸããããããã®ã¡ãœãããçŽæ¥åŒã³åºãããšã§èµ·åããããšãã§ããŸãã
ã³ã³ããã¹ããããŒãžã£ã®ä»£è¡šçãªäœ¿ãæ¹ãšããŠã¯ãæ§ã ãªã°ããŒãã«æ å ±ã®ä¿åããã³æŽæ°ããªãœãŒã¹ã®ããã¯ãšã¢ã³ããã¯ããã¡ã€ã«ã®ãªãŒãã³ãšã¯ããŒãºãªã©ãæããããŸãã
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. ã¯ã©ã¹ãã¿ãŒã³ãããã®äœçœ®åŒæ°ã®ã«ã¹ã¿ãã€ãºÂ¶
ãã¿ãŒã³ã®äžã§ã¯ã©ã¹åãå©çšããå Žåãäœçœ®åŒæ°ã¯ããã©ã«ãã§ã¯å©çšã§ããŸããã MyClass ã§ç¹å¥ãªãµããŒãããªããšã case MyClass(x, y) ã¯éåžžç¡å¹ã§ãããã®ãããªãã¿ãŒã³ãå©çšããã«ã¯ã __match_args__ 屿§ãã¯ã©ã¹ã«å®çŸ©ããå¿
èŠããããŸãã
- object.__match_args__¶
ãã®ã¯ã©ã¹å€æ°ã«ã¯æååã®ã¿ãã«ãã¢ãµã€ã³å¯èœã§ãããã®ã¯ã©ã¹ãã¯ã©ã¹ãã¿ãŒã³ã®äœçœ®åŒæ°ã®äžã§å©çšããããšãããããã®äœçœ®åŒæ°ã¯å¯Ÿå¿ãã __match_args__ ã®äžã®å€ãããŒã¯ãŒããšãããããŒã¯ãŒãåŒæ°ã«å€æãããŸãããã®å±æ§ããªãæã¯ã
()ãèšå®ãããŠããã®ãšå矩ã§ãã
äŸãã°ããã MyClass.__match_args__ ã« ("left", "center", "right") ãå®çŸ©ãããŠããå Žåã case MyClass(x, y) 㯠case MyClass(left=x, center=y) ãšå矩ã§ãããã¿ãŒã³ã®åŒæ°ã®æ°ã¯ã __match_args__ ã®èŠçŽ æ°ãšåçããã以äžã§ãªããã°ãªããªãç¹ã«æ³šæããŠãã ããããããå€ãã£ãå Žåã«ã¯ããã¿ãŒã³ããã㯠TypeError ãéåºããŸãã
Added in version 3.10.
åè
- PEP 634 - æ§é çãã¿ãŒã³ããã
matchæã®è©³çްã
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()
ãã®åäœã®èæ¯ãšãªãçç±ã¯ã __hash__() ãš __repr__() ãšãã£ã type ãªããžã§ã¯ããå«ããã¹ãŠã®ãªããžã§ã¯ãã§å®çŸ©ãããŠããç¹æ®ã¡ãœããã«ãããŸãããããã®ã¡ãœããã®æé»ã®æ€çŽ¢ãéåžžã®æ€çŽ¢ããã»ã¹ã䜿ã£ãå Žåã type ãªããžã§ã¯ãèªäœã«å¯ŸããŠå®è¡ããããšãã«å€±æããŠããŸããŸã:
>>> 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
æ£ç¢ºæ§ã®ããã«ã€ã³ã¹ã¿ã³ã¹å±æ§ãã¹ãããããã®ã«å ããŠãç¹æ®ã¡ãœããæ€çŽ¢ã¯ãªããžã§ã¯ãã®ã¡ã¿ã¯ã©ã¹ãå«ããŠã __getattribute__() ã¡ãœããããã€ãã¹ããŸã:
>>> 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
ãã®ããã« __getattribute__() æ©æ§ããã€ãã¹ããããšã§ãç¹æ®ã¡ãœããã®æ±ãã«é¢ããããçšåºŠã®èªç±åºŠãšåŒãæãã« (ç¹æ®ã¡ãœããã¯ã€ã³ã¿ããªã¿ããäžè²«ããŠå®è¡ãããããã«ã¯ã©ã¹ãªããžã§ã¯ãã«èšå® ããªããã°ãªããªã)ãã€ã³ã¿ãŒããªã¿ãé«éåããããã®å€§ããªäœå°ãæã«å
¥ããŸãã
3.4. ã³ã«ãŒãã³Â¶
3.4.1. åŸ æ©å¯èœãªããžã§ã¯ã (Awaitable Object)¶
awaitable ãªããžã§ã¯ãã¯äžè¬çã«ã¯ __await__() ã¡ãœãããå®è£
ãããŠããŸãã async def 颿°ãè¿ã Coroutineãªããžã§ã¯ã ã¯åŸ
æ©å¯èœã§ãã
泚é
types.coroutine() ãã³ã¬ãŒã¿ã§ãã³ã¬ãŒã¿ãä»ãããããžã§ãã¬ãŒã¿ããè¿ããã generator iterator ãªããžã§ã¯ããåŸ
æ©å¯èœã§ããã __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ãªããžã§ã¯ã 㯠awaitable ãªããžã§ã¯ãã§ãã__await__() ãåŒã³åºãããã®è¿ãå€ã«å¯Ÿãå埩åŠçãããããšã§ã³ã«ãŒãã³ã®å®è¡ãå¶åŸ¡ã§ããŸããã³ã«ãŒãã³ã®å®è¡ãå®äºãå¶åŸ¡ãæ»ãããšããã€ãã¬ãŒã¿ã¯ StopIteration ãéåºãããã®äŸå€ã® value 屿§ã«è¿ãå€ãæãããŸããã³ã«ãŒãã³ãäŸå€ãéåºããå Žåã¯ãã€ãã¬ãŒã¿ã«ããäŒæ¬ãããŸããã³ã«ãŒãã³ãã StopIteration äŸå€ãå€ã«éåºãã¹ãã§ã¯ãããŸããã
ã³ã«ãŒãã³ã«ã¯ä»¥äžã«æããã¡ãœãããããããããã¯ãžã§ãã¬ãŒã¿ã®ã¡ãœããããã®é¡äŒŒã§ã (ãžã§ãã¬ãŒã¿-ã€ãã¬ãŒã¿ã¡ãœãã ãåç §ããŠãã ãã)ã ãã ãããžã§ãã¬ãŒã¿ãšéã£ãŠãã³ã«ãŒãã³ã¯å埩åŠçãçŽæ¥ã¯ãµããŒãããŠããŸããã
Coroutines are generic over the types of their yield, send, and return values, respectively.
ããŒãžã§ã³ 3.5.2 ã§å€æŽ: ã³ã«ãŒãã³ã§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]])
ã³ã«ãŒãã³ã§æå®ãããäŸå€ãéåºããŸãã ãã®ã¡ãœããã¯ãã€ãã¬ãŒã¿ã«ã³ã«ãŒãã³ãäžæåæ¢ãã
throw()ã¡ãœãããããå Žåã«åŠçãå§ä»»ããŸãã ããã§ãªãå Žåã«ã¯ãäžæããå°ç¹ããäŸå€ãéåºãããŸãã çµæ (è¿ãå€ãStopIterationããã®ä»ã®äŸå€) ã¯ãäžã§è§£èª¬ãããããª__await__()ã®è¿ãå€ã«å¯ŸããŠå埩åŠçãè¡ã£ããšããšåãã§ãã äŸå€ãã³ã«ãŒãã³ã®äžã§ææãããªãã£ãå ŽåãåŒã³åºãå ãžäŒæ¬ãããŸããããŒãžã§ã³ 3.12 ã§å€æŽ: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.
- coroutine.close()¶
ã³ã«ãŒãã³ãèªåèªèº«ã®åŸçä»ãããçµäºããŸãã ã³ã«ãŒãã³ãäžæåæ¢ããŠããå Žåã¯ãã³ã«ãŒãã³ãäžæåæ¢ãããã€ãã¬ãŒã¿ã«
close()ã¡ãœãããããã°ããŸãã¯ããã«åŠçãå§ä»»ããŸãã ãããŠäžæåæ¢ããå°ç¹ããGeneratorExitãéåºããããã ã¡ã«ã³ã«ãŒãã³ãèªåèªèº«ã®åŸçä»ããè¡ããŸãã æåŸã«ãå®è¡ãéå§ãããŠããªãã£ãå Žåã§ããã³ã«ãŒãã³ã«å®è¡ãå®äºããå°ãä»ããŸããã³ã«ãŒãã³ãªããžã§ã¯ããç Žæ£ããããšãã«ã¯ãäžèšã®æé ãçµãŠèªåçã«éããããŸãã
3.4.3. éåæã€ãã¬ãŒã¿ (Asynchronous Iterator)¶
éåæã€ãã¬ãŒã¿ ã® __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 ã§å€æŽ: Python 3.7 ããåã§ã¯ã __aiter__() 㯠éåæã€ãã¬ãŒã¿ ã«ãªã awaitable ãè¿ããŸããã
Python 3.7 ããã¯ã __aiter__() ã¯éåæã€ãã¬ãŒã¿ãªããžã§ã¯ããè¿ããªããã°ãªããŸããã
ãã以å€ã®ãã®ãè¿ããš TypeError ã«ãªããŸãã
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.
èæ³š