Cara menggunakan int to binary python

Interpreter Python memiliki sejumlah fungsi dan tipe bawaan di dalamnya yang selalu tersedia. Mereka terdaftar di sini dalam urutan abjad.

Fungsi Bawaan

A


B


C


D


E


F


G


H


I

L


M


N


O


P





R


S


T


V


Z


_

abs(x)

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
05. If the argument is a complex number, its magnitude is returned.

aiter(async_iterable)

Return an for an . Equivalent to calling

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
06.

Note: Unlike , has no 2-argument variant.

Baru pada versi 3.10.

all(iterable)

Kembalikan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 jika semua elemen dari iterable bernilai benar (atau jika iterable kosong). Setara dengan:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

awaitable anext(async_iterator)awaitable anext(async_iterator, default)

When awaited, return the next item from the given , or default if given and the iterator is exhausted.

This is the async variant of the builtin, and behaves similarly.

This calls the method of async_iterator, returning an . Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwise is raised.

Baru pada versi 3.10.

any(iterable)

Kembalikan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 jika ada elemen dari iterable bernilai benar. Jika iterable kosong, kembalikan
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14. Setara dengan:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

ascii(object)

As , return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by using

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
17,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
18, or
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
19 escapes. This generates a string similar to that returned by in Python 2.

bin(x)

Ubah angka bulat atau integer menjadi string biner yang diawali dengan "0b". Hasilnya adalah ekspresi Python yang valid. Jika x bukan objek Python :class: int, ia harus mendefinisikan metode

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 yang mengembalikan integer. Beberapa contoh:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If the prefix "0b" is desired or not, you can use either of the following ways.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

Lihat juga untuk informasi lebih lanjut.

class bool(x=False)

Return a Boolean value, i.e. one of

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 or
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14. x is converted using the standard . If x is false or omitted, this returns
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14; otherwise, it returns
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09. The class is a subclass of (see ). It cannot be subclassed further. Its only instances are
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14 and
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 (see ).

Berubah pada versi 3.7: x sekarang menjadi parameter sesuai-posisi.

breakpoint(*args, **kws)

This function drops you into the debugger at the call site. Specifically, it calls , passing

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
32 and
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
33 straight through. By default,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
31 calls expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly import or type as much code to enter the debugger. However, can be set to some other function and will automatically call that, allowing you to drop into the debugger of choice. If is not accessible, this function will raise .

Memunculkan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
41 dengan argumen
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
42.

Baru pada versi 3.7.

class bytearray(source=b'')class bytearray(source, encoding)class bytearray(source, encoding, errors)

Kembalikan array byte baru. Kelas adalah urutan bilangan bulat yang dapat berubah dalam kisaran 0 <= x <256. Ia memiliki sebagian besar metode urutan-urutan yang dapat berubah, yang dijelaskan dalam , dan juga sebagian besar metode yang dimiliki oleh , lihat .

Parameter opsional source dapat digunakan untuk menginisialisasi array dengan beberapa cara berbeda:

  • Jika ini adalah string, Anda juga harus memberikan parameter encoding (dan opsional, errors); kemudian mengonversi string menjadi byte menggunakan .

  • Jika ini adalah integer, array akan memiliki ukuran itu dan akan diinisialisasi dengan null bytes.

  • Jika itu adalah objek yang sesuai dengan buffer interface, buffer yang hanya baca dari objek tersebut akan digunakan untuk menginisialisasi array byte.

  • Jika ini adalah iterable, itu harus iterable dari bilangan bulat dalam kisaran

    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    47, yang digunakan sebagai konten awal array.

Tanpa argumen, dibuat array berukuran 0.

Lihat juga: ref:binaryseq dan :ref:` typebytearray`.

class bytes(source=b'')class bytes(source, encoding)class bytes(source, encoding, errors)

Return a new "bytes" object which is an immutable sequence of integers in the range

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
47. is an immutable version of -- it has the same non-mutating methods and the same indexing and slicing behavior.

Dengan demikian, argumen konstruktor ditafsirkan untuk .

Objek byte juga dapat dibuat dengan literal, lihat .

Lihat juga , , dan .

callable(object)

Kembalikan jika argumen object tampak dapat dipanggil, jika tidak. Jika ini mengembalikan nilai

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09, masih mungkin bahwa pemanggilan gagal, tetapi jika itu
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14, memanggil object tidak akan pernah berhasil. Perhatikan bahwa kelas dapat dipanggil (memanggil kelas mengembalikan instansi baru); instansi dapat dipanggil jika kelasnya memiliki metode
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
56.

Baru pada versi 3.2: Fungsi ini pertama kali dihapus di Python 3.0 dan kemudian dibawa kembali di Python 3.2.

chr(i)

Kembalikan string yang mewakili karakter dimana titik kode Unicode sebagai integer i. Misalnya,

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
57 mengembalikan string
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
58, sementara
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
59 mengembalikan string
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
60. Ini adalah kebalikan dari .

Rentang yang valid untuk argumen adalah dari 0 hingga 1.114.111 (0x10FFFF dalam basis 16). akan ditimbulkan jika i berada di luar rentang itu.

@classmethod

Ubah metode menjadi metode kelas.

A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2): ...

Bentuk

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
63 adalah fungsi -- lihat untuk detail.

Metode kelas dapat dipanggil baik pada kelas (seperti

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
64) atau pada instance (seperti
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
65). Instance diabaikan kecuali untuk kelasnya. Jika metode kelas dipanggil untuk kelas turunan, objek kelas turunan dilewatkan sebagai argumen pertama yang tersirat.

Class methods are different than C++ or Java static methods. If you want those, see in this section. For more information on class methods, see .

Berubah pada versi 3.9: Class methods can now wrap other such as .

Berubah pada versi 3.10: Class methods now inherit the method attributes (

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
68,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
69,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
70,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
71 and
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
72) and have a new
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
73 attribute.

Berubah pada versi 3.11: Class methods can no longer wrap other such as .

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=- 1)

Kompilasi source menjadi kode atau objek AST. Objek kode dapat dieksekusi oleh atau . source dapat berupa string normal, string byte, atau objek AST. Rujuk ke dokumentasi modul untuk informasi tentang cara bekerja dengan objek AST.

Argumen filename harus memberikan berkas dari mana kode dibaca; berikan nilai yang dapat dikenali jika tidak dibaca dari berkas (

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
78 biasa digunakan).

Argumen mode menentukan jenis kode apa yang harus dikompilasi; itu bisa

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
79 jika source terdiri dari urutan pernyataan,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
80 jika terdiri dari satu ekspresi, atau
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
81 jika terdiri dari satu pernyataan interaktif (dalam kasus terakhir, pernyataan ekspresi yang mengevaluasi sesuatu selain
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82 akan dicetak).

The optional arguments flags and dont_inherit control which should be activated and which should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling . If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it -- the flags (future features and compiler options) in the surrounding code are ignored.

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
84 attribute on the
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
85 instance in the module. can be found in module, with
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
88 prefix.

Argumen optimize menentukan tingkat optimisasi compiler; nilai default

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
89 memilih tingkat optimisasi interpreter seperti yang diberikan oleh opsi . Level eksplisitnya adalah
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91 (tidak ada optimisasi;
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
92 bernilai benar),
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
93 (asserts dihapus,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
92 bernilai salah) atau
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
95 (docstrings juga dihapus ).

Fungsi ini memunculkan jika sumber yang dikompilasi tidak valid, dan jika sumbernya berisi byte null.

Jika Anda ingin mengurai kode Python ke dalam representasi AST-nya, lihat .

Memunculkan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
99 dengan argumen
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
00,
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
01.

Catatan

Ketika mengkompilasi string dengan kode multi-baris dalam mode

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
81 atau
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
80, masukan harus diakhiri oleh setidaknya satu karakter baris baru. Ini untuk memudahkan deteksi pernyataan tidak lengkap dan lengkap dalam modul .

Peringatan

Dimungkinkan untuk membuat crash interpreter Python dengan string yang cukup besar/kompleks ketika dikompilasi ke objek AST karena batasan kedalaman tumpukan dalam kompiler AST Python.

Berubah pada versi 3.2: Allowed use of Windows and Mac newlines. Also, input in

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
79 mode does not have to end in a newline anymore. Added the optimize parameter.

Berubah pada versi 3.5: Sebelumnya, dimunculkan ketika byte null ditemui di source.

Baru pada versi 3.8:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
07 sekarang dapat diberikan tanda untuk mengaktifkan dukungan untuk
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
08,
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
09, dan
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
10 tingkat atas.

class complex(real=0, imag=0)class complex(string)

Kembalikan bilangan kompleks dengan nilai real + imag*1j atau ubah string atau angka menjadi bilangan kompleks. Jika parameter pertama adalah string, itu akan ditafsirkan sebagai bilangan kompleks dan fungsinya harus dipanggil tanpa parameter kedua. Parameter kedua tidak pernah menjadi string. Setiap argumen dapat berupa tipe numerik apa pun (termasuk kompleks). Jika imag dihilangkan, defaultnya adalah nol dan pembangun constructor berfungsi sebagai konversi numerik seperti dan . Jika kedua argumen dihilangkan, kembalikan

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
13.

Untuk objek Python umum

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
14,
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
15 didelegasikan ke
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
16. Jika
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
17 tidak didefinisikan maka beralih ke
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
18. Jika
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
18 tidak didefinisikan maka beralih ke
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21.

Catatan

Saat mengkonversi dari string, string tidak boleh berisi spasi whitespace di sekitar operator

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
21 atau
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
22 pusat. Misalnya,
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
23 baik-baik saja, tetapi
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
24 menimbulkan .

Tipe kompleks dijelaskan dalam .

Berubah pada versi 3.6: Pengelompokan angka dengan garis bawah seperti dalam literal kode diperbolehkan.

Berubah pada versi 3.8: Dialihkan ke

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 jika
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
17 dan
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
18 tidak terdefinisi.

delattr(object, name)

This is a relative of . The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example,

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
30 is equivalent to
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
31. name need not be a Python identifier (see ).

class dict(**kwarg)class dict(mapping, **kwarg)class dict(iterable, **kwarg)

Buat dictionary baru. Objek adalah kelas kamus dictionary. Lihat dan untuk dokumentasi tentang kelas ini.

Untuk wadah containers lain, lihat kelas-kelas bawaan :class: list, , dan , dan juga modul .

dir()dir(object)

Tanpa argumen, kembalikan daftar list nama dalam lingkup lokal saat ini. Dengan argumen, mencoba untuk mengembalikan daftar list atribut yang valid untuk objek itu.

Jika objek memiliki metode bernama

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
38, metode ini akan dipanggil dan harus mengembalikan daftar atribut. Ini memungkinkan objek yang mengimplementasikan fungsi alihsuai custom
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
39 atau
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
40 untuk menyesuaikan cara melaporkan atributnya.

If the object does not provide

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
38, the function tries its best to gather information from the object's attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
39.

Mekanisme bawaan berperilaku berbeda dengan berbagai jenis objek, karena berusaha menghasilkan informasi yang paling relevan, dibanding lengkap,:

  • Jika objek adalah objek modul, daftar berisi nama-nama atribut modul.

  • Jika objek adalah tipe atau objek kelas, daftar berisi nama atributnya, dan secara rekursif atribut dari basisnya.

  • Jika tidak, daftar berisi nama atribut objek, nama atribut kelasnya, dan secara rekursif atribut dari kelas dasar kelasnya.

Daftar yang dihasilkan diurutkan berdasarkan abjad. Sebagai contoh:

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

Catatan

Karena disediakan terutama sebagai kenyamanan untuk digunakan pada prompt interaktif, ia mencoba untuk memasok sekumpulan nama yang menarik lebih dari sekedar untuk menyediakan sekumpulan nama yang didefinisikan secara ketat atau konsisten, dan perilakunya yang terperinci dapat berubah lintas rilis. Misalnya, atribut metaclass tidak ada dalam daftar hasil ketika argumennya adalah kelas.

divmod(a, b)

Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
47. For floating point numbers the result is
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
48, where q is usually
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
49 but may be 1 less than that. In any case
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
50 is very close to a, if
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
51 is non-zero it has the same sign as b, and
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
52.

enumerate(iterable, start=0)

Kembalikan objek enumerasi. iterable harus berupa urutan, sebuah , atau objek lain yang mendukung iterasi. The metode iterator dikembalikan oleh mengembalikan tuple yang berisi hitungan (dari start yang bawaan ke 0) dan nilai yang diperoleh dari mengelilingi iterable.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Setara dengan:

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1

eval(expression, globals=None, locals=None)

Argumennya adalah string dan opsional global dan lokal. Jika disediakan, globals harus berupa dictionary. Jika disediakan, locals dapat berupa objek pemetaan apa pun.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
55, a reference to the dictionary of the built-in module is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
55 dictionary into globals before passing it to . If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where is called. Note, eval() does not have access to the (non-locals) in the enclosing environment.

Nilai kembalian adalah hasil dari ekspresi yang dievaluasi. Kesalahan sintaks dilaporkan sebagai pengecualian. Contoh:

>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by ). In this case, pass a code object instead of a string. If the code object has been compiled with

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
79 as the mode argument, 's return value will be
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82.

Hints: dynamic execution of statements is supported by the function. The and functions return the current global and local dictionary, respectively, which may be useful to pass around for use by or .

If the given source is a string, then leading and trailing spaces and tabs are stripped.

Lihat untuk fungsi yang dapat dengan aman mengevaluasi string dengan ekspresi yang hanya mengandung literal.

Memunculkan

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
70 dengan argumen
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
71.

exec(object, globals=None, locals=None, /, *, closure=None)

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section in the Reference Manual). Be aware that the , , and statements may not be used outside of function definitions even within the context of code passed to the function. The return value is

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

Jika dictionary globals tidak mengandung nilai untuk kunci

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
55, referensi ke dictionary modul bawaan dimasukkan di bawah kunci itu. Dengan begitu Anda dapat mengontrol bawaan apa yang tersedia untuk kode yang dieksekusi dengan memasukkan dictionary
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
55 Anda sendiri ke globals sebelum meneruskannya ke .

The closure argument specifies a closure--a tuple of cellvars. It's only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.

Memunculkan

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
70 dengan argumen
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
71.

Catatan

Fungsi bawaan :func: globals dan masing-masing mengembalikan dictionary global dan lokal, yang mungkin berguna untuk digunakan sebagai argumen kedua dan ketiga untuk .

Catatan

Bawaan locals bertindak seperti yang dijelaskan untuk fungsi di bawah: modifikasi ke dictionary locals default tidak boleh dicoba. Melewatkan dictionary *locals eksplisit jika Anda perlu melihat efek kode pada locals setelah fungsi mengembalikan.

Berubah pada versi 3.11: Added the closure parameter.

filter(function, iterable)

Bangun sebuah iterator dari elemen-elemen iterable yang functions mengembalikan benar. iterable dapat berupa urutan, wadah container yang mendukung iterasi, atau iterator. Jika function adalah

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82, fungsi identitas diasumsikan, yaitu, semua elemen iterable yang salah dihapus.

Perhatikan bahwa

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
88 setara dengan ekspresi generator
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
89 jika function tidak
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82 dan
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
91 if function adalah
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82.

Lihat untuk fungsi komplementer yang mengembalikan elemen iterable yang berfungsi function mengembalikan salah.

class float(x=0.0)

Kembalikan angka pecahan floating point yang dibangun dari angka atau string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
94 or
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
95; a
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
94 sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to the
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
97 production rule in the following grammar, after leading and trailing whitespace characters are removed:

sign        ::=  "+" | "-"
infinity    ::=  "Infinity" | "inf"
nan         ::=  "nan"
digitpart   ::=  digit (["_"] digit)*
number      ::=  [digitpart] "." digitpart | digitpart ["."]
exponent    ::=  ("e" | "E") ["+" | "-"] digitpart
floatnumber ::=  number [exponent]
floatvalue  ::=  [sign] (floatnumber | infinity | nan)

Here

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
98 is a Unicode decimal digit (character in the Unicode general category
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
99). Case is not significant, so, for example, "inf", "Inf", "INFINITY", and "iNfINity" are all acceptable spellings for positive infinity.

Kalau tidak, jika argumennya adalah bilangan bulat atau angka pecahan floating point, angka pecahan dengan nilai yang sama (dalam presisi floating point Python) dikembalikan. Jika argumen di luar kisaran float Python, akan dimunculkan.

Untuk objek Python umum

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
14,
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
02 didelegasikan ke
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
03. Jika
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
18 tidak terdefinisi maka beralih ke
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21.

Jika tidak ada argumen yang diberikan, dikembalikan sebagai

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
06.

Contoh:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
0

Tipe float dijelaskan dalam .

Berubah pada versi 3.6: Pengelompokan angka dengan garis bawah seperti dalam literal kode diperbolehkan.

Berubah pada versi 3.7: x sekarang menjadi parameter sesuai-posisi.

Berubah pada versi 3.8: Dialihkan ke

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 jika
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
18 tidak terdefinisi.

format(value, format_spec='')

Convert a value to a "formatted" representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: .

Default format_spec adalah string kosong yang biasanya memberikan efek yang sama dengan memanggil .

Pemanggilan ke

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
10 diterjemahkan ke
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
11 yang memintas instance dictionary saat mencari nilai dari methode . Pengecualian exception dimunculkan jika pencarian metode mencapai dan format_spec tidak kosong, atau jika format_spec atau nilai kembalian bukan string.

Berubah pada versi 3.4:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
14 menimbulkan jika format_spec bukan string kosong.

class frozenset(iterable=set())

Kembalikan objek baru , secara opsional dengan elemen yang diambil dari iterable.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
16 adalah kelas bawaan. Lihat dan untuk dokumentasi tentang kelas ini.

Untuk wadah containers lain lihat kelas-kelas bawaan , ,: class: tuple, dan , serta modul .

getattr(object, name)getattr(object, name, default)

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example,

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
23 is equivalent to
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
24. If the named attribute does not exist, default is returned if provided, otherwise is raised. name need not be a Python identifier (see ).

Catatan

Since happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to retrieve it with .

globals()

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

hasattr(object, name)

Argumen adalah objek dan string. Hasilnya adalah

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 jika string adalah nama salah satu atribut objek,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14 jika tidak. (Ini diimplementasikan dengan memanggil
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
30 dan melihat apakah itu memunculkan atau tidak.)

hash(object)

Kembalikan nilai hash objek (jika ada). Nilai hash adalah bilangan bulat. Mereka digunakan untuk dengan cepat membandingkan kunci kamus dictionary keys selama pencarian dictionary. Nilai numerik yang membandingkan sama memiliki nilai hash yang sama (bahkan jika mereka dari jenis yang berbeda, seperti halnya untuk 1 dan 1.0).

Catatan

Untuk objek dengan metode ubahsuai custom

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
32, perhatikan bahwa memotong atau mengosongkan kembali nilai berdasarkan lebar bit mesin host. Lihat
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
32 untuk detailnya.

help()help(request)

Meminta sistem bantuan bawaan. (Fungsi ini dimaksudkan untuk penggunaan interaktif.) Jika tidak ada argumen yang diberikan, sistem bantuan interaktif dimulai pada konsol interpreter. Jika argumennya adalah string, maka string tersebut dicari sebagai nama modul, fungsi, kelas, metode, kata kunci, atau topik dokumentasi, dan halaman bantuan dicetak pada konsol. Jika argumennya adalah objek jenis apa pun, halaman bantuan tentang objek tersebut dihasilkan.

Note that if a slash(/) appears in the parameter list of a function when invoking , it means that the parameters prior to the slash are positional-only. For more info, see .

Fungsi ini ditambahkan ke namespace bawaan dengan modul .

Berubah pada versi 3.4: Perubahan ke dan berarti bahwa tanda tangan signatures yang dilaporkan untuk callables sekarang lebih komprehensif dan konsisten.

hex(x)

Ubah angka integer menjadi string heksadesimal huruf kecil yang diawali dengan "0x". Jika x bukan objek Python , ia harus mendefinisikan metode

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 yang mengembalikan integer. Beberapa contoh:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
1

Jika Anda ingin mengonversi bilangan bulat menjadi string heksadesimal huruf besar atau huruf kecil dengan awalan atau tidak, Anda dapat menggunakan salah satu dari cara berikut:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
2

Lihat juga untuk informasi lebih lanjut.

Lihat juga untuk mengonversi string heksadesimal menjadi integer menggunakan basis 16.

Catatan

Untuk mendapatkan representasi string heksadesimal untuk float, gunakan metode .

id(object)

Kembalikan "identity" suatu objek. Ini adalah bilangan bulat yang dijamin unik dan konstan untuk objek ini selama masa pakainya. Dua objek dengan masa hidup yang tidak tumpang tindih mungkin memiliki nilai yang sama .

Detail implementasi CPython: This is the address of the object in memory.

Memunculkan sebuah auditing event

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
45 dengan argumen
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
46.

input()input(prompt)

Jika argumen prompt ada, ini ditulis ke keluaran standar tanpa baris tambahan. Fungsi ini kemudian membaca sebuah baris dari masukan, mengubahnya menjadi sebuah string (menghapus baris baru yang tertinggal), dan mengembalikannya. Ketika EOF dibaca, dimunculkan. Contoh:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
3

Jika modul dimuat, maka akan menggunakannya untuk menyediakan fitur pengeditan baris dan riwayat.

Memunculkan

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
50 dengan argumen
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
51.

Memunculkan

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
52 dengan argumen
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
53.

class int(x=0)class int(x, base=10)

Kembalikan objek integer yang dibangun dari angka atau string x, atau kembalikan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91 jika tidak ada argumen yang diberikan. Jika x mendefinisikan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
55,
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
56 mengembalikan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
57. Jika x mendefinisikan
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21, ia mengembalikan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
59. Jika x mendefinisikan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
60, ia mengembalikan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
61. Untuk angka floating point, ini memotong menuju nol.

If x is not a number or if base is given, then x must be a string, , or instance representing an integer in radix base. Optionally, the string can be preceded by

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
21 or
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
22 (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.

A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0--9 can be represented by any Unicode decimal digit. The values 10--35 can be represented by

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
66 to
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
67 (or
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
68 to
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
69). The default base is 10. The allowed bases are 0 and 2--36. Base-2, -8, and -16 strings can be optionally prefixed with
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
70/
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
71,
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
72/
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
73, or
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
74/
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
75, as with integer literals in code. For base 0, the string is interpreted in a similar way to an , in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros:
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
76 is not legal, while
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
77 and
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
78 are.

Tipe integer dijelaskan dalam .

Berubah pada versi 3.4: Jika base bukan turunan dari dan objek base memiliki metode

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
80, metode itu dipanggil untuk mendapatkan integer untuk basis. Versi sebelumnya digunakan
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
81 alih-alih :meth: base.__index__ <objek .__ index __>.

Berubah pada versi 3.6: Pengelompokan angka dengan garis bawah seperti dalam literal kode diperbolehkan.

Berubah pada versi 3.7: x sekarang menjadi parameter sesuai-posisi.

Berubah pada versi 3.8: Dialihkan ke

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 jika
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
55 tidak terdefinisi.

Berubah pada versi 3.11: The delegation to

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
60 is deprecated.

Berubah pada versi 3.11: string inputs and string representations can be limited to help avoid denial of service attacks. A is raised when the limit is exceeded while converting a string x to an or when converting an into a string would exceed the limit. See the documentation.

isinstance(object, classinfo)

Return

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or ) subclass thereof. If object is not an object of the given type, the function always returns
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14. If classinfo is a tuple of type objects (or recursively, other such tuples) or a of multiple types, return
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a exception is raised. may not be raised for an invalid type if an earlier check succeeds.

Berubah pada versi 3.10: classinfo can be a .

issubclass(class, classinfo)

Return

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 if class is a subclass (direct, indirect, or ) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a , in which case return
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 if class is a subclass of any entry in classinfo. In any other case, a exception is raised.

Berubah pada versi 3.10: classinfo can be a .

iter(object)iter(object, sentinel)

Return an object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the protocol (the

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
97 method), or it must support the sequence protocol (the
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
98 method with integer arguments starting at
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91). If it does not support either of those protocols, is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its method; if the value returned is equal to sentinel, will be raised, otherwise the value will be returned.

Lihat juga .

Salah satu kegunaan dari bentuk kedua dari adalah untuk membangun pembaca blok. Misalnya, membaca blok dengan lebar tetap dari berkas basis data biner hingga akhir file tercapai:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
4

len(s)

Mengembalikan panjang (jumlah item) suatu objek. Argumennya bisa berupa urutan (seperti string, byte, tuple, list, atau range) atau koleksi (seperti dictionary, set, atau frozen set).

Detail implementasi CPython:

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
04 raises on lengths larger than , such as .

class listclass list(iterable)

Alih-alih menjadi sebuah fungsi, sebenarnya adalah tipe urutan yang bisa berubah mutable, seperti yang didokumentasikan dalam dan :ref: typesseq.

locals()

Perbarui dan kembalikan dictionary yang mewakili tabel simbol lokal saat ini. Variabel bebas dikembalikan oleh saat dipanggil dalam blok fungsi, tetapi tidak di blok kelas. Perhatikan bahwa pada tingkat modul, dan adalah dictionary yang sama.

Catatan

Isi dictionary ini tidak boleh dimodifikasi; perubahan mungkin tidak mempengaruhi nilai variabel lokal dan bebas yang digunakan oleh interpreter.

map(function, iterable, *iterables)

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see .

max(iterable, *, key=None)max(iterable, *, default, key=None)max(arg1, arg2, *args, key=None)

Kembalikan item terbesar dalam iterable atau yang terbesar dari dua atau lebih argumen.

Jika satu argumen posisi disediakan, itu harus berupa . Item terbesar di iterable dikembalikan. Jika dua atau lebih argumen posisi disediakan, argumen posisi terbesar dikembalikan.

Ada dua opsional hanya argumen kata kunci keyword arguments. Argumen key menentukan fungsi pengurutan satu argumen seperti yang digunakan untuk . Argumen default menentukan objek yang akan dikembalikan jika yang disediakan itu kosong. Jika iterable kosong dan default tidak disediakan, akan dimunculkan.

Jika beberapa item maksimal, fungsi mengembalikan item pertama yang ditemui. Ini konsisten dengan alat pengawet preserving sortir yang stabil lain seperti

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
15 dan
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
16.

Baru pada versi 3.4: default hanya argumen kata kunci keyword argument.

Berubah pada versi 3.8: key bisa jadi

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82.

class memoryview(object)

Kembalikan objek "memory view" yang dibuat dari argumen yang diberikan. Lihat untuk informasi lebih lanjut.

min(iterable, *, key=None)min(iterable, *, default, key=None)min(arg1, arg2, *args, key=None)

Kembalikan item terkecil dalam iterable atau terkecil dari dua atau lebih argumen.

Jika satu argumen posisi disediakan, itu harus berupa . Item terkecil di iterable dikembalikan. Jika dua atau lebih argumen posisional disediakan, argumen posisional terkecil akan dikembalikan.

Ada dua opsional hanya argumen kata kunci keyword arguments. Argumen key menentukan fungsi pengurutan satu argumen seperti yang digunakan untuk . Argumen default menentukan objek yang akan dikembalikan jika yang disediakan itu kosong. Jika iterable kosong dan default tidak disediakan, akan dimunculkan.

Jika beberapa item minimal, fungsi mengembalikan item pertama yang ditemui. Ini konsisten dengan alat pengawet preserving sortir yang stabil lain seperti

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
20 dan
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
21.

Baru pada versi 3.4: default hanya argumen kata kunci keyword argument.

Berubah pada versi 3.8: key bisa jadi

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82.

next(iterator)next(iterator, default)

Retrieve the next item from the by calling its method. If default is given, it is returned if the iterator is exhausted, otherwise is raised.

class object

Return a new featureless object. is a base for all classes. It has methods that are common to all instances of Python classes. This function does not accept any arguments.

Catatan

not memiliki

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
43, jadi Anda tidak dapat menetapkan atribut arbitrary ke turunan dari kelas .

oct(x)

Ubah angka integer menjadi string oktal yang diawali dengan "0o". Hasilnya adalah ekspresi Python yang valid. Jika x bukan objek Python :class: int, ia harus mendefinisikan metode

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
21 yang mengembalikan integer. Sebagai contoh:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
5

If you want to convert an integer number to an octal string either with the prefix "0o" or not, you can use either of the following ways.

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
6

Lihat juga untuk informasi lebih lanjut.

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Buka file dan mengembalikan yang sesuai dengan . Jika file tersebut tidak dapat dibuka, sebuah akan dinaikkan. Lihat untuk contoh yang lebih banyak terkait bagaimana menggunakan fungsi ini.

file is a giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
33 which means open for reading in text mode. Other common values are
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
34 for writing (truncating the file if it already exists),
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
35 for exclusive creation, and
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
58 for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent: is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

Karakter

Artinya

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
33

terbuka untuk membaca (bawaan)

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
34

buka untuk menulis, mengosongkan berkas terlebih dahulu

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
35

terbuka untuk pembuatan eksklusif, gagal jika file sudah ada

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
58

open for writing, appending to the end of file if it exists

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
42

mode biner

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
43

mode teks (bawaan)

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
94

terbuka untuk memperbarui (membaca dan menulis)

The default mode is

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
33 (open for reading text, a synonym of
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
46). Modes
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
47 and
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
48 open and truncate the file. Modes
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
49 and
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
50 open the file with no truncation.

Seperti disebutkan dalam , Python membedakan antara biner dan teks I/O. Berkas dibuka dalam mode biner (termasuk

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
42 dalam argumen mode) mengembalikan konten sebagai objek tanpa decoding. Dalam mode teks (bawaan, atau ketika
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
43 termasuk dalam argumen mode), isi file dikembalikan sebagai , byte yang pertama kali diterjemahkan decoded menggunakan encoding bergantung-platform atau menggunakan encoding yang ditentukan jika diberikan.

Catatan

Python tidak tergantung pada gagasan sistem operasi yang mendasari file teks; semua pemrosesan dilakukan oleh Python sendiri, dan oleh karena itu tidak bergantung platform.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
55 (i.e., files opened with
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
56) would have another buffering. To disable buffering in
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
55, consider using the
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
58 flag for . When no buffering argument is given, the default buffering policy works as follows:

  • File biner disangga buffered dalam potongan ukuran tetap; ukuran penyangga dipilih menggunakan heuristik yang mencoba menentukan "block size" perangkat yang mendasarinya dan bergantung pada . Pada banyak sistem, panjang penyangga biasanya adalah 4096 atau 8192 byte.

  • Berkas teks "interactive" (berkas yang mengembalikan

    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    09) menggunakan line buffering. File teks lainnya menggunakan kebijakan yang dijelaskan di atas untuk file biner.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever returns), but any supported by Python can be used. See the module for the list of supported encodings.

errors adalah string opsional yang menentukan bagaimana kesalahan encoding dan decoding ditangani — ini tidak dapat digunakan dalam mode biner. Berbagai penangan kesalahan standar tersedia (terdaftar di bawah ), meskipun nama penanganan kesalahan yang telah terdaftar dengan juga valid. Nama standar meliputi:

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    66 untuk memunculkan pengecualian jika ada kesalahan penyandian encoding. Nilai bawaan dari
    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    82 memiliki efek yang sama.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    69 mengabaikan kesalahan. Perhatikan bahwa mengabaikan kesalahan penyandian encoding dapat menyebabkan hilangnya data.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    70 menyebabkan penanda pengganti (seperti
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    71) disisipkan di mana ada data yang tidak sesuai format.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    72 will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    73 error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    74 hanya didukung saat menulis ke berkas. Karakter yang tidak didukung oleh penyandian encoding diganti dengan referensi karakter XML yang sesuai
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    75.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    76 menggantikan data yang salah dengan urutan pemisahan dengan backslash dari Python.

  • class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    77 (juga hanya didukung saat menulis) menggantikan karakter yang tidak didukung dengan
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    78 urutan pemisahan.

newline determines how to parse newline characters from the stream. It can be

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82,
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
80,
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
81,
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
82, and
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
83. It works as follows:

  • Saat membaca masukan dari aliran stream, jika newline adalah

    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    82, mode universal baris baru diaktifkan. Baris dalam masukan dapat diakhiri dengan
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    81,
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    82, atau
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    83, dan ini diterjemahkan ke dalam
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    81 sebelum dikembalikan ke pemanggil. Jika
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    80, mode baris baru universal diaktifkan, tetapi akhir baris dikembalikan ke pemanggil yang tidak diterjemahkan. Jika memiliki salah satu nilai legal lainnya, jalur masukan hanya diakhiri oleh string yang diberikan, dan akhir baris dikembalikan ke pemanggil yang tidak diterjemahkan.

  • Saat menulis keluaran ke aliran stream, jika newline adalah

    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    82, setiap karakter
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    81 yang ditulis diterjemahkan ke pemisah garis bawaan sistem, . Jika newline adalah
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    80 atau
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    81, tidak ada terjemahan yang terjadi. Jika newline adalah salah satu dari nilai legal lainnya, setiap karakter
    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    81 yang ditulis diterjemahkan ke string yang diberikan.

If closefd is

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
14 and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09 (the default); otherwise, an error will be raised.

Pembuka khusus dapat digunakan dengan melewatkan callable sebagai opener. Deskriptor berkas yang mendasari untuk objek berkas kemudian diperoleh dengan memanggil opener dengan (file, flags). opener harus mengembalikan deskriptor berkas terbuka (lewat sebagai opener menghasilkan fungsionalitas yang mirip dengan melewatkan

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82).

Berkas yang baru dibuat adalah .

Contoh berikut menggunakan parameter dari fungsi untuk membuka berkas relatif ke direktori yang diberikan:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
7

Tipe yang dikembalikan oleh fungsi tergantung pada mode. Ketika digunakan untuk membuka berkas dalam mode teks (

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
34,
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
33,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
05,
class C:
    @classmethod
    def f(cls, arg1, arg2): ...
46, dll.), ia mengembalikan subkelas dari (khusus ). Ketika digunakan untuk membuka file dalam mode biner dengan buffering, kelas yang dikembalikan adalah subkelas dari . Kelas yang tepat bervariasi: dalam mode baca biner, ia mengembalikan ; dalam mode tulis biner dan append biner, ia mengembalikan sebuah , dan dalam mode baca/tulis, ia mengembalikan sebuah . Ketika buffering dinonaktifkan, aliran tak diproses raw stream, subkelas dari , , dikembalikan.

See also the file handling modules, such as , (where is declared), , , , and .

Memunculkan

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
22 dengan argumen
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
23,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
24,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
25.

Argumen

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
24 dan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
25 mungkin telah dimodifikasi atau disimpulkan dari pemanggilan asli.

Berubah pada versi 3.3:

  • Parameter opener telah ditambahkan.

  • Mode

    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    35 telah ditambahkan.

  • sebelumnya ditimbulkan, sekarang merupakan alias dari .

  • sekarang ditimbulkan jika berkas yang dibuka dalam mode pembuatan eksklusif (

    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    35) sudah ada.

Berubah pada versi 3.4:

  • Berkas sekarang tidak dapat diwariskan.

Berubah pada versi 3.5:

  • Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian (lihat PEP 475 untuk penjelasannya).

  • Penangan kesalahan

    class C:
        @classmethod
        def f(cls, arg1, arg2): ...
    
    77 telah ditambahkan.

Berubah pada versi 3.6:

  • Dukungan ditambahkan untuk menerima objek yang mengimplementasikan .

  • Di Windows, membuka penyangga buffer konsol dapat mengembalikan subclass dari selain .

Berubah pada versi 3.11: The

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
38 mode has been removed.

ord(c)

Diberikan string yang mewakili satu karakter Unicode, kembalikan integer yang mewakili titik kode Unicode dari karakter itu. Misalnya,

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
39 mengembalikan integer
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
40 dan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
41 (tanda Euro) mengembalikan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
42. Ini adalah kebalikan dari .

pow(base, exp, mod=None)

Kembalikan base ke power exp; jika mod ada, kembalikan base ke power exp, modulo mod (dihitung lebih efisien daripada

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
44). Bentuk dua argumen
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
45 setara dengan menggunakan operator power:
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
46.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
48 returns
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
49, but
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
50 returns
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
51. For a negative base of type or and a non-integral exponent, a complex result is delivered. For example,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
54 returns a value close to
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
55.

Untuk operan base dan exp, jika mod ada, mod juga harus bertipe integer dan mod harus bukan nol. Jika mod ada dan exp negatif, basis harus relatif prima ke mod. Dalam kasus itu,

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
57 dikembalikan, di mana inv_base adalah kebalikan dari base modulo mod.

Berikut adalah contoh penghitungan kebalikan untuk

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
58 modulo
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
40:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
8

Berubah pada versi 3.8: Untuk operan , bentuk tiga argumen dari

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
61 sekarang memungkinkan argumen kedua menjadi negatif, memungkinkan perhitungan inverse modular.

Berubah pada versi 3.8: Izinkan argumen kata kunci keyword arguments. Sebelumnya, hanya argumen posisi yang didukung.

print(*objects, sep=' ', end='\n', file=None, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.

Semua argumen non-kata kunci dikonversi ke string seperti dan ditulis ke aliran stream, dipisahkan oleh sep dan diikuti oleh end. Baik sep dan end harus berupa string; mereka juga bisa

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82, yang berarti menggunakan nilai bawaan. Jika tidak ada objects yang diberikan, hanya akan menulis end.

Argumen file harus berupa objek dengan metode

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
65; jika tidak ada atau
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82, akan digunakan. Karena argumen yang dicetak dikonversi ke string teks, tidak dapat digunakan dengan objek file mode biner. Untuk ini, gunakan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
69 sebagai gantinya.

Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Berubah pada versi 3.3: Menambahkan argumen kata kunci flush.

class property(fget=None, fset=None, fdel=None, doc=None)

Kembalikan atribut properti.

fget adalah fungsi untuk mendapatkan nilai atribut. fset adalah fungsi untuk mengatur nilai atribut. fdel adalah fungsi untuk menghapus nilai atribut. Dan doc membuat docstring untuk atribut.

Penggunaan khasnya untuk mendefinisikan atribut yang dikelola

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
14:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
9

If c is an instance of C,

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
71 will invoke the getter,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
72 will invoke the setter, and
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
73 the deleter.

Jika diberikan, doc akan menjadi docstring dari atribut properti. Jika tidak, properti akan menyalin docstring dari fget (jika ada). Ini memungkinkan untuk membuat properti baca-saja read-only dengan mudah menggunakan sebagai :

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
0

Decorator

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
75 mengubah metode
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
76 menjadi "getter" untuk atribut baca-saja read-only dengan nama yang sama, dan mengatur docstring untuk voltage menjadi "Get the current voltage."

Properti dari objek memiliki: attr:~property.getter,

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
77, dan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
78 metode yang dapat digunakan sebagai dekorator yang membuat salinan properti dengan fungsi accessor yang sesuai. diatur ke fungsi yang didekorasi. Ini paling baik dijelaskan dengan contoh:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
1

Kode ini persis sama dengan contoh pertama. Pastikan untuk memberi fungsi tambahan nama yang sama dengan properti asli (

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
14 dalam kasus ini.)

Properti dari objek yang dikembalikan juga memiliki atribut

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
80,
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
81, dan
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
82 yang sesuai dengan argumen pembangun constructor.

Berubah pada versi 3.5: docstrings dari properti objek-objek sekarang dapat ditulisi.

class range(stop)class range(start, stop, step=1)

Alih-alih menjadi fungsi, sebenarnya merupakan tipe urutan yang tidak dapat diubah immutable, seperti yang didokumentasikan dalam dan .

repr(object)

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to ; otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
85 method. If is not accessible, this function will raise .

reversed(seq)

Kembalikan kebalikan dari . seq harus berupa objek yang memiliki

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
88 metode atau dukungan protokol urutan (metode
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
89 dan metode
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
98 dengan argumen integer mulai dari
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91 ).

round(number, ndigits=None)

Kembalikan number dibulatkan ke ndigits presisi setelah titik desimal. Jika ndigits dihilangkan atau

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82, ini akan mengembalikan integer terdekat ke masukannya.

For the built-in types supporting , values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both

>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
94 and
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
95 are
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91, and
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
97 is
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
95). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82. Otherwise, the return value has the same type as number.

Untuk sebuah objek Python

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
00 secara umum,
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
01 mendelegasikan ke
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
02.

Catatan

Perilaku untuk pecahan floats bisa mengejutkan: misalnya,

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
04 memberikan
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
05 alih-alih yang diharapkan
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
06. Ini bukan bug: ini adalah hasil dari fakta bahwa sebagian besar pecahan desimal tidak dapat diwakili persis seperti pelampung float. Lihat untuk informasi lebih lanjut.

class setclass set(iterable)

Kembalikan objek baru , secara opsional dengan elemen yang diambil dari iterable.

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
35 adalah kelas bawaan. Lihat: class:set dan untuk dokumentasi tentang kelas ini.

Untuk wadah containers lain lihat kelas-kelas bawaan , , , dan , juga modul .

setattr(object, name, value)

This is the counterpart of . The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
15 is equivalent to
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
16.

name need not be a Python identifier as defined in unless the object chooses to enforce that, for example in a custom or via . An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible through etc..

Catatan

Since happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to set it with .

class slice(stop)class slice(start, stop, step=1)

Return a object representing the set of indices specified by

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
21. The start and step arguments default to
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82. Slice objects have read-only data attributes
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
23,
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
24, and
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
25 which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages. Slice objects are also generated when extended indexing syntax is used. For example:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
26 or
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
27. See for an alternate version that returns an iterator.

sorted(iterable, /, *, key=None, reverse=False)

Kembalikan daftar baru yang diurutkan dari item di iterable.

Memiliki dua argumen opsional yang harus ditentukan sebagai argumen kata kunci.

key menentukan sebuah fungsi dari satu argumen yang digunakan untuk mengekstrak kunci perbandingan dari setiap elemen di iterable (misalnya,

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
29). Nilai bawaannya adalah
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
82 (bandingkan elemen secara langsung).

reverse adalah nilai boolean. Jika diatur ke

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
09, maka elemen list atau daftar diurutkan seolah-olah setiap perbandingan dibalik.

Gunakan untuk mengubah fungsi cmp gaya lama menjadi fungsi key.

Fungsi bawaan dijamin stabil. Semacam stabil jika menjamin tidak mengubah urutan relatif elemen yang membandingkan kesamaan --- ini berguna untuk menyortir dalam beberapa langkah (misalnya, urutkan berdasarkan departemen, lalu dengan tingkat gaji).

The sort algorithm uses only

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
34 comparisons between items. While defining an method will suffice for sorting, PEP 8 recommends that all six be implemented. This will help avoid bugs when using the same data with other ordering tools such as that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the method.

Untuk contoh pengurutan dan tutorial singkat pengurutan, lihat :ref: sortinghowto.

@staticmethod

Ubah sebuah metode menjadi sebuah metode statis.

Metode statis tidak menerima argumen implisit pertama. Untuk mendeklarasikan metode statis, gunakan idiom ini:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
2

Bentuk

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
38 adalah fungsi -- lihat untuk detail.

A static method can be called either on the class (such as

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
64) or on an instance (such as
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
65). Moreover, they can be called as regular functions (such as
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
41).

Static methods in Python are similar to those found in Java or C++. Also, see for a variant that is useful for creating alternate class constructors.

Seperti semua dekorator, dimungkinkan juga untuk memanggil

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
43 sebagai fungsi biasa dan melakukan sesuatu dengan hasilnya. Ini diperlukan dalam beberapa kasus di mana Anda memerlukan referensi ke fungsi dari badan kelas dan Anda ingin menghindari transformasi otomatis ke metode instance. Untuk kasus ini, gunakan idiom ini:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
3

Untuk informasi lebih lanjut tentang metode statis, lihat .

Berubah pada versi 3.10: Static methods now inherit the method attributes (

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
68,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
69,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
70,
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
71 and
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
72), have a new
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
73 attribute, and are now callable as regular functions.

class str(object='')class str(object=b'', encoding='utf-8', errors='strict')

Kembalikan sebuah versi dari objek. Lihat untuk detailnya.

class C:
    @classmethod
    def f(cls, arg1, arg2): ...
54 adalah string bawaan . Untuk informasi umum tentang string, lihat .

sum(iterable, /, start=0)

Jumlah start dan item dari iterable dari kiri ke kanan dan mengembalikan total. Item iterable biasanya berupa angka, dan nilai awal tidak boleh berupa string.

Untuk beberapa kasus penggunaan, ada alternatif yang baik untuk . Cara yang disukai dan cepat untuk menggabungkan rangkaian string adalah dengan memanggil

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
54. Untuk menambahkan nilai pecahan floating point dengan presisi yang diperluas, lihat . Untuk menggabungkan serangkaian iterables, coba gunakan .

Berubah pada versi 3.8: Parameter mulai dapat ditentukan sebagai argumen kata kunci.

class superclass super(type, object_or_type=None)

Kembalikan objek proxy yang mendelegasikan panggilan metode ke kelas orang tua atau saudara dari type. Ini berguna untuk mengakses metode yang diwariskan yang telah ditimpa di suatu kelas.

The object_or_type determines the to be searched. The search starts from the class right after the type.

For example, if of object_or_type is

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
58 and the value of type is
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
59, then searches
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
61.

The attribute of the object_or_type lists the method resolution search order used by both and . The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

Jika argumen kedua dihilangkan, objek super yang dikembalikan tidak terikat unbound. Jika argumen kedua adalah objek,

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
65 harus benar. Jika argumen kedua adalah tipe,
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
66 harus benar (ini berguna untuk metode-metode kelas).

Ada dua kasus penggunaan khas untuk super. Dalam hierarki kelas dengan pewarisan tunggal single inheritance, super dapat digunakan untuk merujuk ke kelas induk tanpa menyebutkannya secara eksplisit, sehingga membuat kode lebih mudah dikelola. Penggunaan ini sangat mirip dengan penggunaan super dalam bahasa pemrograman lain.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

Untuk kedua kasus penggunaan, pemanggilan superclass yang khas terlihat seperti ini:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
4

Selain pencarian metode, juga berfungsi untuk pencarian atribut. Salah satu kemungkinan kasus penggunaan ini adalah pemanggilan di kelas induk atau saudara kandung.

Perhatikan bahwa diimplementasikan sebagai bagian dari proses pengikatan binding untuk pencarian atribut eksplisit bertitik dotted seperti

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
69. Itu melakukannya dengan menerapkan sendiri metode
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
40 untuk mencari kelas dalam urutan terprediksi yang mendukung multiple inheritance kooperatif. Dengan demikian, tidak ditentukan untuk pencarian implisit menggunakan pernyataan atau operator seperti
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
72.

Juga perhatikan bahwa, selain dari bentuk tanpa argumen, tidak terbatas untuk menggunakan metode di dalam. Bentuk dua argumen menentukan argumen dengan tepat dan membuat referensi yang sesuai. Bentuk tanpa argumen hanya bekerja di dalam definisi kelas, karena compiler mengisi rincian yang diperlukan untuk mengambil kelas yang didefinisikan dengan benar, serta mengakses instance saat ini untuk metode biasa.

Untuk saran praktis tentang bagaimana merancang kelas kooperatif menggunakan , lihat guide to using super().

class tupleclass tuple(iterable)

Alih-alih menjadi fungsi, sebenarnya merupakan tipe urutan yang tidak dapat diubah atau disebut immutable, seperti yang didokumentasikan dalam dan .

class type(object)class type(name, bases, dict, **kwds)

Dengan satu argumen, kembalikan tipe dari sebuah object. Nilai kembaliannya adalah sebuah tipe objek dan umumnya objek yang sama seperti yang dikembalikan oleh .

Fungsi bawaan direkomendasikan untuk menguji jenis objek, karena ia memperhitungkan subkelas.

With three arguments, return a new type object. This is essentially a dynamic form of the statement. The name string is the class name and becomes the attribute. The bases tuple contains the base classes and becomes the attribute; if empty, , the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the attribute. The following two statements create identical objects:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
5

Lihat juga .

Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually ) in the same way that keywords in a class definition (besides metaclass) would.

See also .

Berubah pada versi 3.6: Subkelas dari yang tidak menimpa

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
86 mungkin tidak lagi menggunakan bentuk satu argumen untuk mendapatkan tipe dari suatu objek.

vars()vars(object)

Kembalikan atribut: attr:~object.__ dict__ untuk modul, kelas, instance, atau objek lainnya yang memiliki atribut

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
87.

Objek seperti modul dan instance memiliki atribut yang dapat diperbarui ; namun, objek lain mungkin memiliki batasan penulisan pada atribut (misalnya, kelas menggunakan sebuah untuk mencegah pembaruan kamus secara langsung).

Tanpa argumen, bertindak seperti . Catatan, dictionary lokal hanya berguna untuk dibaca karena pembaruan ke dictionary lokal diabaikan.

Sebuah pengecualian untuk akan muncul jika suatu objek yang ditentukan tetapi tidak memiliki sebuah atribut (contohnya, jika suatu kelas didefinisikan sebagai atribut ).

zip(*iterables, strict=False)

Iterate over several iterables in parallel, producing tuples with an item from each one.

Example:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
6

More formally: returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.

Another way to think of is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix.

is lazy: The elements won't be processed until the iterable is iterated on, e.g. by a

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
99 loop or by wrapping in a .

One thing to consider is that the iterables passed to could have different lengths; sometimes by design, and sometimes because of a bug in the code that prepared these iterables. Python offers three different approaches to dealing with this issue:

  • By default, stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:

    >>> bin(3)
    '0b11'
    >>> bin(-10)
    '-0b1010'
    
    7

  • is often used in cases where the iterables are assumed to be of equal length. In such cases, it's recommended to use the

    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    04 option. Its output is the same as regular :

    >>> bin(3)
    '0b11'
    >>> bin(-10)
    '-0b1010'
    
    8

    Unlike the default behavior, it raises a if one iterable is exhausted before the others:

    >>> bin(3)
    '0b11'
    >>> bin(-10)
    '-0b1010'
    
    9

    Without the

    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    04 argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.

  • Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by .

Edge cases: With a single iterable argument, returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

Tips and tricks:

  • The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using

    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    10. This repeats the same iterator
    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    11 times so that each output tuple has the result of
    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    11 calls to the iterator. This has the effect of dividing the input into n-length chunks.

  • bersama dengan operator

    def enumerate(iterable, start=0):
        n = start
        for elem in iterable:
            yield n, elem
            n += 1
    
    14 dapat digunakan untuk unzip sebuah list atau daftar:

    >>> format(14, '#b'), format(14, 'b')
    ('0b1110', '1110')
    >>> f'{14:#b}', f'{14:b}'
    ('0b1110', '1110')
    
    0

Berubah pada versi 3.10: Added the

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
15 argument.

__import__(name, globals=None, locals=None, fromlist=(), level=0)

Catatan

Ini adalah fungsi lanjutan yang tidak diperlukan dalam pemrograman Python sehari-hari, tidak seperti .

Fungsi ini dipanggil oleh pernyataan . Itu dapat diganti (dengan mengimpor modul dan mengisi ke

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
19) untuk mengubah semantik pernyataan
def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
17, tetapi melakukannya strongly atau tidak disarankan karena biasanya lebih mudah menggunakan kait impor (lihat: pep:302) untuk mencapai tujuan yang sama dan tidak menyebabkan masalah dengan kode yang mengasumsikan implementasi impor standar sedang digunakan. Penggunaan langsung juga tidak disarankan untuk kepentingan .

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the statement.

level menentukan apakah akan menggunakan impor absolut atau relatif.

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
91 (bawaan) berarti hanya melakukan impor absolut. Nilai positif untuk level menunjukkan jumlah direktori induk untuk mencari relatif ke direktori pemanggilan modul (lihat PEP 328 untuk detailnya).

Ketika variabel name dalam bentuk

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
26, biasanya, paket tingkat atas (nama hingga titik pertama) dikembalikan, not modul dinamai dengan name. Namun, ketika argumen tidak-kosong fromlist * diberikan, modul bernama oleh *name dikembalikan.

Sebagai contoh, pernyataan

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
27 menghasilkan bytecode yang menyerupai kode berikut:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
1

Pernyataan

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
28 menghasilkan panggilan ini:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
2

Perhatikan caranya mengembalikan modul tingkat atas di sini karena ini adalah objek yang terikat pada nama oleh pernyataan .

Di sisi lain, pernyataan

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
31 menghasilkan

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
3

Di sini, modul

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
32 dikembalikan dari . Dari objek ini, nama yang akan diimpor diambil dan diisikan ke nama masing-masing.

Jika Anda hanya ingin mengimpor sebuah modul (berpotensi dalam suatu paket) dengan nama, gunakan .

Berubah pada versi 3.3: Nilai negatif untuk level tidak lagi didukung (juga mengubah nilai default menjadi 0).

Berubah pada versi 3.9: When the command line options or are being used, the environment variable is now ignored.

Catatan kaki

Perhatikan bahwa pengurai hanya menerima konvensi akhir garis end of line gaya Unix. Jika Anda membaca kode dari sebuah berkas, pastikan untuk menggunakan mode konversi baris baru untuk mengkonversi baris baru gaya Windows atau Mac.