Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. Some examples of iterables are tuples, strings, and lists
Syntax
list(iterable)Parameter
- iterable. an object that could be a sequence (string, tuples) or collection (set, dictionary) or any iterator object
Note. If we don’t pass any parameter then the list() function will return a list with zero elements (empty list)
Mari kita lihat beberapa contoh untuk pemahaman yang lebih baik
Contoh 1. Menggunakan list() untuk membuat daftar dari string
Piton
# initializing a string
string= "ABCDEF"
# using list() function to create a list
['A', 'B', 'C', 'D', 'E', 'F']0= ['A', 'B', 'C', 'D', 'E', 'F']2['A', 'B', 'C', 'D', 'E', 'F']3
['A', 'B', 'C', 'D', 'E', 'F']_4
['A', 'B', 'C', 'D', 'E', 'F']_5['A', 'B', 'C', 'D', 'E', 'F']6
Keluaran
['A', 'B', 'C', 'D', 'E', 'F']_Contoh 2. Menggunakan list() untuk membuat daftar dari tuple
Piton
['A', 'B', 'C', 'D', 'E', 'F']_7
['A', 'B', 'C', 'D', 'E', 'F']8= ['A', 'B', 'C', 'D', 'E']0['A', 'B', 'C', 'D', 'E']1['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']3['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']5['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']7________10_['A', 'B', 'C', 'D', 'E', 'F']_091
# using list() function to create a list
['A', 'B', 'C', 'D', 'E', 'F']0= ['A', 'B', 'C', 'D', 'E', 'F']2['C', 'E', 'D', 'B', 'A'] ['A', 'B', 'C', 'D', 'E']5
['A', 'B', 'C', 'D', 'E', 'F']_4
['A', 'B', 'C', 'D', 'E', 'F']_5['A', 'B', 'C', 'D', 'E', 'F']6
Keluaran
['A', 'B', 'C', 'D', 'E']Contoh 3. Menggunakan list() untuk membuat daftar dari set dan kamus
Piton
['C', 'E', 'D', 'B', 'A'] ['A', 'B', 'C', 'D', 'E']_9
________29______0= Please Enter List Elements: 12345 ['1', '2', '3', '4', '5']2['A', 'B', 'C', 'D', 'E']1['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']3['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']5['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']7_______10____10_['A', 'B', 'C', 'D', 'E', 'F']4
# initializing a string_3
# initializing a string4= Please Enter List Elements: 12345 ['1', '2', '3', '4', '5']2['A', 'B', 'C', 'D', 'E']1# initializing a string8# initializing a string9['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']3# initializing a string8string3['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']5# initializing a string8string7['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']7# initializing a string8=1['A', 'B', 'C', 'D', 'E']2['A', 'B', 'C', 'D', 'E']9# initializing a string8=5# initializing a string2
=_7
['A', 'B', 'C', 'D', 'E', 'F']0= ['A', 'B', 'C', 'D', 'E', 'F']2"ABCDEF"1
"ABCDEF"2= ['A', 'B', 'C', 'D', 'E', 'F']2"ABCDEF"5
"ABCDEF"_6
['A', 'B', 'C', 'D', 'E', 'F']_5['A', 'B', 'C', 'D', 'E', 'F']6
['A', 'B', 'C', 'D', 'E', 'F']_5# using list() function to create a list0
Keluaran
['C', 'E', 'D', 'B', 'A'] ['A', 'B', 'C', 'D', 'E']Kita juga bisa menggunakan fungsi list() saat mengambil input dari user untuk langsung mengambil input berupa list
Interpreter Python memiliki sejumlah fungsi dan tipe bawaan 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)Mengembalikan nilai absolut dari sebuah angka. Argumen dapat berupa bilangan bulat, angka floating point, atau objek yang mengimplementasikan def any(iterable): for element in iterable: if element: return True return False 05. Jika argumennya adalah bilangan kompleks, besarnya dikembalikan
aiter(async_iterable)Kembalikan an untuk an. Setara dengan menelepon def any(iterable): for element in iterable: if element: return True return False _06
Catatan. Tidak seperti , tidak memiliki varian 2-argumen
Baru di versi 3. 10
semua(dapat diubah)Kembalikan def any(iterable): for element in iterable: if element: return True return False _09 jika semua elemen iterable benar (atau jika iterable kosong). Setara dengan
def all(iterable): for element in iterable: if not element: return False return True
dapat ditunggu berikutnya(async_iterator)dapat ditunggu berikut(async_iterator , default)Saat menunggu, kembalikan item berikutnya dari yang diberikan, atau default jika diberikan dan iterator habis
Ini adalah varian async dari builtin, dan berperilaku serupa
Ini memanggil metode async_iterator, mengembalikan an. Menunggu ini mengembalikan nilai berikutnya dari iterator. Jika default diberikan, dikembalikan jika iterator habis, jika tidak dinaikkan
Baru di versi 3. 10
apa saja(dapat diubah)Kembalikan def any(iterable): for element in iterable: if element: return True return False _09 jika ada elemen iterable yang 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(objek)Sebagai , kembalikan string yang berisi representasi objek yang dapat dicetak, tetapi hindari karakter non-ASCII dalam string yang dikembalikan dengan menggunakan 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, atau def any(iterable): for element in iterable: if element: return True return False 19 lolos. Ini menghasilkan string yang mirip dengan yang dikembalikan oleh di Python 2
bin(x)Mengonversi bilangan bulat menjadi string biner yang diawali dengan "0b". Hasilnya adalah ekspresi Python yang valid. Jika x bukan objek Python, ia harus mendefinisikan metode def any(iterable): for element in iterable: if element: return True return False 22 yang mengembalikan bilangan bulat. Beberapa contoh
>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
Jika awalan “0b” diinginkan atau tidak, Anda dapat menggunakan salah satu cara berikut
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
Lihat juga untuk informasi lebih lanjut
kelas bool(x=Salah)Mengembalikan nilai Boolean, mis. e. salah satu dari def any(iterable): for element in iterable: if element: return True return False _09 atau def any(iterable): for element in iterable: if element: return True return False 14. x dikonversi menggunakan standar. Jika x salah atau dihilangkan, ini mengembalikan def any(iterable): for element in iterable: if element: return True return False 14; . Kelas adalah subkelas dari (lihat ). Itu tidak dapat disubklasifikasikan lebih lanjut. Satu-satunya contohnya adalah def any(iterable): for element in iterable: if element: return True return False 14 dan def any(iterable): for element in iterable: if element: return True return False 09 (lihat )
Berubah di versi 3. 7. x sekarang menjadi parameter khusus posisi.
breakpoint(*args , **kws)Fungsi ini membawa Anda ke debugger di situs panggilan. Secara khusus, ini memanggil , melewati def any(iterable): for element in iterable: if element: return True return False _33 dan def any(iterable): for element in iterable: if element: return True return False 34 langsung melalui. Secara default, panggilan def any(iterable): for element in iterable: if element: return True return False _32 tidak mengharapkan argumen. Dalam hal ini, ini murni fungsi kenyamanan sehingga Anda tidak perlu mengimpor atau mengetik kode secara eksplisit untuk memasukkan debugger. Namun, dapat diatur ke beberapa fungsi lain dan secara otomatis akan memanggilnya, memungkinkan Anda untuk masuk ke debugger pilihan. Jika tidak dapat diakses, fungsi ini akan dinaikkan
Memunculkan def any(iterable): for element in iterable: if element: return True return False _42 dengan argumen def any(iterable): for element in iterable: if element: return True return False 43
Baru di versi 3. 7
kelas bytearray(sumber=b'')kelas bytearray(sumber , enkode)kelas bytearray(sumber , enkode , kesalahan)Kembalikan array byte baru. Kelas adalah urutan bilangan bulat yang bisa berubah dalam rentang 0 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): ... 59 (i. e. , files opened with class C: @classmethod def f(cls, arg1, arg2): ... 60) would have another buffering. To disable buffering in class C: @classmethod def f(cls, arg1, arg2): ... 59, consider using the class C: @classmethod def f(cls, arg1, arg2): ... 62 flag for . When no buffering argument is given, the default buffering policy works as follows
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on . On many systems, the buffer will typically be 4096 or 8192 bytes long
“Interactive” text files (files for which returns def any(iterable): for element in iterable: if element: return True return False 09) use line buffering. Other text files use the policy described above for binary files
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 is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under ), though any error handling name that has been registered with is also valid. The standard names include
class C: @classmethod def f(cls, arg1, arg2): ... 70 to raise a exception if there is an encoding error. The default value of def any(iterable): for element in iterable: if element: return True return False 83 has the same effect
class C: @classmethod def f(cls, arg1, arg2): ... 73 ignores errors. Note that ignoring encoding errors can lead to data loss
class C: @classmethod def f(cls, arg1, arg2): ... 74 causes a replacement marker (such as class C: @classmethod def f(cls, arg1, arg2): ... 75) to be inserted where there is malformed data
class C: @classmethod def f(cls, arg1, arg2): ... 76 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): ... 77 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): ... 78 is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference class C: @classmethod def f(cls, arg1, arg2): ... 79
class C: @classmethod def f(cls, arg1, arg2): ... _80 mengganti data yang salah bentuk dengan urutan escape backslash Python
class C: @classmethod def f(cls, arg1, arg2): ... _81 (juga hanya didukung saat menulis) mengganti karakter yang tidak didukung dengan class C: @classmethod def f(cls, arg1, arg2): ... 82 escape sequence
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 83, class C: @classmethod def f(cls, arg1, arg2): ... 84, class C: @classmethod def f(cls, arg1, arg2): ... 85, class C: @classmethod def f(cls, arg1, arg2): ... 86, and class C: @classmethod def f(cls, arg1, arg2): ... 87. It works as follows
Saat membaca input dari aliran, jika baris baru adalah def any(iterable): for element in iterable: if element: return True return False 83, mode baris baru universal diaktifkan. Lines in the input can end in class C: @classmethod def f(cls, arg1, arg2): ... 85, class C: @classmethod def f(cls, arg1, arg2): ... 86, or class C: @classmethod def f(cls, arg1, arg2): ... 87, and these are translated into class C: @classmethod def f(cls, arg1, arg2): ... 85 before being returned to the caller. If it is class C: @classmethod def f(cls, arg1, arg2): ... 84, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated
When writing output to the stream, if newline is def any(iterable): for element in iterable: if element: return True return False 83, any class C: @classmethod def f(cls, arg1, arg2): ... 85 characters written are translated to the system default line separator, . If newline is class C: @classmethod def f(cls, arg1, arg2): ... 84 or class C: @classmethod def f(cls, arg1, arg2): ... 85, no translation takes place. If newline is any of the other legal values, any class C: @classmethod def f(cls, arg1, arg2): ... 85 characters written are translated to the given string
Jika closefd adalah def any(iterable): for element in iterable: if element: return True return False _14 dan deskriptor file daripada nama file diberikan, deskriptor file yang mendasarinya akan tetap terbuka saat file ditutup. 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
A custom opener can be used by passing a callable as opener. Deskriptor file yang mendasari untuk objek file kemudian diperoleh dengan memanggil pembuka dengan (file, flags). pembuka harus mengembalikan deskriptor file terbuka (melewati sebagai pembuka menghasilkan fungsionalitas yang mirip dengan meneruskan def any(iterable): for element in iterable: if element: return True return False _83)
File yang baru dibuat adalah
Contoh berikut menggunakan parameter fungsi untuk membuka file relatif terhadap direktori tertentu
def any(iterable): for element in iterable: if element: return True return False _7
Jenis yang dikembalikan oleh fungsi tergantung pada mode. Kapan digunakan untuk membuka file dalam mode teks (class C: @classmethod def f(cls, arg1, arg2): ... 38, class C: @classmethod def f(cls, arg1, arg2): ... 37, >>> 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'] 09, class C: @classmethod def f(cls, arg1, arg2): ... 50, dll. ), ia mengembalikan subkelas dari (khususnya ). Saat 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 ; . Saat buffering dinonaktifkan, aliran mentah, subkelas dari , , dikembalikan
Lihat juga modul penanganan file, seperti , (di mana dinyatakan), , , , dan
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'] _26 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'] 27, >>> 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'] 28, >>> 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'] 29
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'] 28 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'] 29 mungkin telah dimodifikasi atau disimpulkan dari panggilan asli
Berubah di versi 3. 3
Parameter pembuka telah ditambahkan
Mode class C: @classmethod def f(cls, arg1, arg2): ... _39 telah ditambahkan
dulu dinaikkan, sekarang menjadi alias
sekarang dimunculkan jika file dibuka dalam mode pembuatan eksklusif (class C: @classmethod def f(cls, arg1, arg2): ... 39) sudah ada
Berubah di versi 3. 4
File tersebut sekarang tidak dapat diwariskan
Berubah di versi 3. 5
Jika panggilan sistem terganggu dan penangan sinyal tidak memunculkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih memunculkan pengecualian (lihat PEP 475 untuk alasannya)
Handler kesalahan ________90______81 telah ditambahkan
Berubah di versi 3. 6
Dukungan ditambahkan untuk menerima penerapan objek
Di Windows, membuka buffer konsol dapat mengembalikan subkelas selain
Berubah di versi 3. 11. Mode >>> 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 telah dihapus.
ord(c)Diberi string yang mewakili satu karakter Unicode, kembalikan bilangan bulat yang mewakili titik kode Unicode dari karakter tersebut. 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'] _43 mengembalikan bilangan bulat >>> 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 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'] 45 (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'] 46. Ini kebalikan dari
pow(base , exp , mod=Tidak ada)Kembalikan basis ke exp daya; . 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'] 49 setara dengan menggunakan operator listrik. >>> 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
Argumen harus memiliki tipe numerik. Dengan tipe operan campuran, aturan paksaan untuk operator aritmatika biner berlaku. Untuk operan, hasilnya memiliki tipe yang sama dengan operan (setelah pemaksaan) kecuali jika argumen kedua adalah negatif; . 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'] _52 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'] 53, tetapi >>> 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 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'] 55. Untuk basis tipe negatif atau dan eksponen non-integral, hasil yang kompleks diberikan. 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'] _58 mengembalikan nilai yang mendekati >>> 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'] 59
Untuk operan basis dan exp, jika ada mod, mod juga harus bertipe integer dan mod harus bukan nol. Jika mod ada dan exp negatif, basis harus relatif prima terhadap mod. Dalam hal ini, >>> 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 dikembalikan, di mana inv_base adalah kebalikan dari mod modulo dasar
Berikut adalah contoh penghitungan invers 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'] 62 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'] 44
def any(iterable): for element in iterable: if element: return True return False _8
Berubah di 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'] 65 sekarang mengizinkan argumen kedua menjadi negatif, memungkinkan penghitungan invers modular.
Berubah di versi 3. 8. Izinkan argumen kata kunci. Sebelumnya, hanya argumen posisi yang didukung.
mencetak(*objects , sep=' ' , end='\n' , file=None , flush=Salah)Cetak objek ke file aliran teks, dipisahkan dengan sep dan diikuti dengan akhir. sep, end, file, dan flush, jika ada, harus diberikan sebagai argumen kata kunci
Semua argumen non-kata kunci diubah menjadi string seperti yang dilakukan dan ditulis ke aliran, dipisahkan dengan sep dan diikuti dengan akhir. Baik sep dan end harus berupa string; . Jika tidak ada objek yang diberikan, hanya akan menulis akhir
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'] 69; . Karena argumen tercetak dikonversi menjadi 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'] _73 sebagai gantinya
Apakah output di-buffer biasanya ditentukan oleh file, tetapi jika argumen kata kunci flush benar, aliran akan di-flush secara paksa
Berubah di versi 3. 3. Menambahkan argumen kata kunci flush.
kelas property(fget=None , fset=None , fdel=None , doc=Tidak ada)Mengembalikan 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 tersebut
Penggunaan umum adalah untuk mendefinisikan atribut terkelola >>> bin(3) '0b11' >>> bin(-10) '-0b1010' 15
def any(iterable): for element in iterable: if element: return True return False _9
Jika c adalah instance dari 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'] _75 akan memanggil 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'] 76 akan memanggil setter, 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'] 77 deleter
Jika diberikan, doc akan menjadi docstring dari atribut properti. Jika tidak, properti akan menyalin docstring fget (jika ada). Ini memungkinkan untuk membuat properti hanya-baca dengan mudah menggunakan sebagai a
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' _0
Dekorator >>> 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'] 79 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'] 80 menjadi "pengambil" untuk atribut read-only dengan nama yang sama, dan menetapkan docstring untuk tegangan menjadi "Dapatkan tegangan arus. ”
Objek properti 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'] _81, >>> 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, 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'] 83 metode yang dapat digunakan sebagai dekorator yang membuat salinan properti dengan fungsi pengakses yang sesuai yang diatur ke fungsi yang didekorasi. Ini paling baik dijelaskan dengan sebuah contoh
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' _1
Kode ini persis sama dengan contoh pertama. Pastikan untuk memberikan fungsi tambahan nama yang sama dengan properti asli (>>> bin(3) '0b11' >>> bin(-10) '-0b1010' 15 dalam hal ini. )
The returned property object also has the attributes >>> 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, >>> 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'] 86, 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'] 87 corresponding to the constructor arguments
Changed in version 3. 5. The docstrings of property objects are now writeable.
class range(stop)class range(start , stop , step=1)Rather than being a function, is actually an immutable sequence type, as documented in and
repr(objek)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'] 90 method. If is not accessible, this function will raise
reversed(seq)Return a reverse . seq must be an object which has 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'] 93 method or supports the sequence protocol (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'] 94 method and the class C: @classmethod def f(cls, arg1, arg2): ... 01 method with integer arguments starting at def any(iterable): for element in iterable: if element: return True return False 92)
round(number , ndigits=Tidak ada)Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is def any(iterable): for element in iterable: if element: return True return False 83, it returns the nearest integer to its input
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'] 99 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')] 00 are def any(iterable): for element in iterable: if element: return True return False 92, 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')] 02 is def any(iterable): for element in iterable: if element: return True return False 96). 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 83. Otherwise, the return value has the same type as number
For a general Python object >>> 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, >>> 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 delegates 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')] 07
Note
The behavior of for floats can be surprising. 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')] 09 gives >>> 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')] 10 instead of the expected >>> 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')] 11. This is not a bug. it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See for more information
class setclass set(dapat diubah)Return a new object, optionally with elements taken from iterable. >>> bin(3) '0b11' >>> bin(-10) '-0b1010' 37 is a built-in class. See and for documentation about this class
For other containers see the built-in , , , and classes, as well as the module
setattr(object , name , value)This is the counterpart of . Argumennya adalah objek, string, dan nilai arbitrer. String dapat menamai atribut yang ada atau atribut baru. 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')] 21 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')] 22
name need not be a Python identifier as defined in unless the object chooses to enforce that, for example in a custom or via . Atribut yang namanya bukan pengidentifikasi tidak akan dapat diakses menggunakan notasi titik, tetapi dapat diakses melalui dll
Note
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')] 27. The start and step arguments default to def any(iterable): for element in iterable: if element: return True return False 83. 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')] 29, >>> 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')] 30, 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')] 31 which merely return the argument values (or their default). Mereka tidak memiliki fungsi eksplisit lainnya; . 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')] _32 atau >>> 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')] 33. Lihat untuk versi alternatif yang mengembalikan iterator
sorted(iterable , / , * , key=None , reverse=Salah)Kembalikan daftar terurut baru dari item di iterable
Memiliki dua argumen opsional yang harus ditentukan sebagai argumen kata kunci
kunci menentukan fungsi dari satu argumen yang digunakan untuk mengekstrak kunci perbandingan dari setiap elemen dalam 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')] 35). Nilai defaultnya adalah def any(iterable): for element in iterable: if element: return True return False 83 (bandingkan elemen secara langsung)
terbalik adalah nilai boolean. Jika diatur ke def any(iterable): for element in iterable: if element: return True return False 09, maka elemen daftar diurutkan seolah-olah setiap perbandingan dibalik
Gunakan untuk mengonversi fungsi cmp gaya lama menjadi fungsi kunci
Fungsi bawaan dijamin stabil. Pengurutan stabil jika menjamin untuk tidak mengubah urutan relatif elemen yang sebanding — ini berguna untuk menyortir dalam beberapa lintasan (misalnya, mengurutkan berdasarkan departemen, kemudian berdasarkan tingkat gaji)
Algoritme pengurutan hanya menggunakan >>> 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')] _40 perbandingan antar item. Sementara mendefinisikan sebuah metode akan cukup untuk penyortiran, PEP 8 merekomendasikan agar keenamnya diimplementasikan. Ini akan membantu menghindari bug saat menggunakan data yang sama dengan alat pengurutan lain seperti yang bergantung pada metode dasar yang berbeda. Menerapkan keenam perbandingan juga membantu menghindari kebingungan untuk perbandingan tipe campuran yang dapat memanggil metode yang tercermin
Untuk contoh penyortiran dan tutorial penyortiran singkat, lihat
@staticmethodMengubah metode menjadi 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')] _44 adalah fungsi – lihat detailnya
Metode statis dapat dipanggil baik di kelas (seperti def any(iterable): for element in iterable: if element: return True return False 65) atau di instance (seperti def any(iterable): for element in iterable: if element: return True return False 66). Selain itu, mereka dapat disebut sebagai fungsi biasa (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')] 47)
Metode statis di Python mirip dengan yang ditemukan di Java atau C++. Lihat juga varian yang berguna untuk membuat konstruktor kelas alternatif
Seperti semua dekorator, juga dimungkinkan 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')] 49 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 di versi 3. 10. Metode statis sekarang mewarisi atribut metode (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, def any(iterable): for element in iterable: if element: return True return False 72 dan def any(iterable): for element in iterable: if element: return True return False 73), memiliki atribut def any(iterable): for element in iterable: if element: return True return False 74 baru, dan sekarang dapat dipanggil sebagai fungsi biasa.
kelas str(object='')class str(objek=b'' , encoding='utf-8' , errors='strict')Mengembalikan versi objek. Lihat detailnya
class C: @classmethod def f(cls, arg1, arg2): ... _58 adalah string bawaan. Untuk informasi umum tentang string, lihat
jumlah(iterable , / , mulai=0)Penjumlahan dimulai dan item iterable dari kiri ke kanan dan mengembalikan totalnya. Item iterable biasanya berupa angka, dan nilai awal tidak boleh berupa string
Untuk beberapa kasus penggunaan, ada alternatif yang bagus untuk. Cara yang disukai dan cepat untuk menggabungkan urutan 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')] 60. Untuk menambahkan nilai floating point dengan presisi yang diperluas, lihat. Untuk menggabungkan serangkaian iterables, pertimbangkan untuk menggunakan
Berubah di versi 3. 8. Parameter awal dapat ditentukan sebagai argumen kata kunci.
kelas superclass super(type , object_or_type=Tidak ada)Mengembalikan objek proxy yang mendelegasikan panggilan metode ke kelas tipe induk atau saudara. Ini berguna untuk mengakses metode warisan yang telah diganti di kelas
object_or_type menentukan yang akan dicari. Pencarian dimulai dari kelas tepat setelah tipe
Misalnya, jika object_or_type adalah >>> 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')] 64 dan nilai type adalah >>> 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, maka cari >>> 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')] 67
Atribut object_or_type mencantumkan urutan pencarian resolusi metode yang digunakan oleh dan. Atributnya dinamis dan dapat berubah setiap kali hierarki pewarisan diperbarui
Jika argumen kedua dihilangkan, objek super yang dikembalikan tidak terikat. If the second argument is an object, >>> 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')] 71 must be true. 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')] 72 harus benar (ini berguna untuk metode kelas)
Ada dua kasus penggunaan umum untuk super. Dalam hierarki kelas dengan pewarisan tunggal, super dapat digunakan untuk merujuk ke kelas induk tanpa menamainya secara eksplisit, sehingga membuat kode lebih mudah dipelihara. Penggunaan ini sangat mirip dengan penggunaan super dalam bahasa pemrograman lain
Kasus penggunaan kedua adalah untuk mendukung pewarisan berganda kooperatif dalam lingkungan eksekusi yang dinamis. Kasus penggunaan ini unik untuk Python dan tidak ditemukan dalam bahasa yang dikompilasi secara statis atau bahasa yang hanya mendukung pewarisan tunggal. Hal ini memungkinkan untuk menerapkan "diamond diagram" di mana beberapa kelas dasar menerapkan metode yang sama. Desain yang baik menyatakan bahwa implementasi seperti itu memiliki tanda pemanggilan yang sama di setiap kasus (karena urutan panggilan ditentukan saat waktu proses, karena urutan tersebut menyesuaikan dengan perubahan dalam hierarki kelas, dan karena urutan tersebut dapat menyertakan kelas saudara yang tidak diketahui sebelum waktu proses
Untuk kedua kasus penggunaan, panggilan superclass biasanya terlihat seperti ini
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' _4
Selain pencarian metode, juga berfungsi untuk pencarian atribut. Salah satu kasus penggunaan yang mungkin untuk ini adalah memanggil kelas orang tua atau saudara kandung
Catatan yang diimplementasikan sebagai bagian dari proses pengikatan untuk pencarian atribut bertitik eksplisit 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')] 75. Ia melakukannya dengan menerapkan metode >>> bin(3) '0b11' >>> bin(-10) '-0b1010' _42 miliknya sendiri untuk mencari kelas dalam urutan yang dapat diprediksi yang mendukung pewarisan berganda kooperatif. Oleh karena itu, 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')] 78
Perhatikan juga bahwa, selain bentuk argumen nol, tidak terbatas pada penggunaan metode di dalam. Bentuk dua argumen menentukan argumen dengan tepat dan membuat referensi yang sesuai. Bentuk argumen nol hanya berfungsi di dalam definisi kelas, karena kompiler mengisi detail yang diperlukan untuk mengambil kelas yang didefinisikan dengan benar, serta mengakses instance saat ini untuk metode biasa.
Untuk saran praktis tentang cara mendesain kelas kooperatif menggunakan , lihat panduan menggunakan super()
kelas tupleclass tuple(dapat diubah)Rather than being a function, is actually an immutable sequence type, as documented in and
kelas type(object)class type(name , bases , dict , **kwds)Dengan satu argumen, kembalikan jenis objek. Nilai yang dikembalikan adalah objek bertipe dan umumnya objek yang sama dengan yang dikembalikan oleh
Fungsi bawaan direkomendasikan untuk menguji jenis objek, karena memperhitungkan subkelas
Dengan tiga argumen, kembalikan objek tipe baru. Ini pada dasarnya adalah bentuk pernyataan yang dinamis. String nama adalah nama kelas dan menjadi atribut. Tuple basis berisi kelas dasar dan menjadi atribut; . Kamus dict berisi definisi atribut dan metode untuk badan kelas; . Dua pernyataan berikut membuat objek yang identik
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' 5
See also
Argumen kata kunci yang diberikan ke tiga bentuk argumen diteruskan ke mesin metaclass yang sesuai (biasanya ) dengan cara yang sama seperti kata kunci dalam definisi kelas (selain metaclass) akan
See also
Berubah di versi 3. 6. Subkelas yang tidak ditimpa >>> 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')] 92 mungkin tidak lagi menggunakan formulir satu argumen untuk mendapatkan tipe objek.
var()vars(objek)Mengembalikan atribut untuk modul, kelas, instance, atau objek lain dengan atribut
Objek seperti modul dan instans memiliki atribut yang dapat diperbarui;
Tanpa argumen, bertindak seperti. Catatan, kamus lokal hanya berguna untuk dibaca karena pembaruan kamus lokal diabaikan
Pengecualian dimunculkan jika objek ditentukan tetapi tidak memiliki atribut (misalnya, jika kelasnya menentukan atribut)
zip(*iterables , strict=Salah)Ulangi beberapa iterable secara paralel, menghasilkan tupel dengan item dari masing-masingnya
Contoh
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' _6
Lebih formal. mengembalikan iterator tupel, di mana tupel ke-i berisi elemen ke-i dari setiap argumen iterables
Cara lain untuk memikirkannya adalah mengubah baris menjadi kolom, dan kolom menjadi baris. Ini mirip dengan mentranspos matriks
malas. Elemen tidak akan diproses sampai iterable diaktifkan, mis. g. dengan loop def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 _06 atau dengan membungkus a
Satu hal yang perlu dipertimbangkan adalah iterables yang diteruskan dapat memiliki panjang yang berbeda; . Python menawarkan tiga pendekatan berbeda untuk menangani masalah ini
Secara default, berhenti saat iterable terpendek habis. Ini akan mengabaikan item yang tersisa di iterables yang lebih lama, memotong hasilnya dengan panjang iterable terpendek
>>> bin(3) '0b11' >>> bin(-10) '-0b1010' _7
sering digunakan dalam kasus di mana iterables diasumsikan memiliki panjang yang sama. Dalam kasus seperti itu, disarankan untuk menggunakan opsi def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 11. Outputnya sama dengan reguler
>>> 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
Tanpa def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 11 argumen, setiap bug yang menghasilkan iterables dengan panjang yang berbeda akan dibungkam, mungkin bermanifestasi sebagai bug yang sulit ditemukan di bagian lain dari program
Iterables yang lebih pendek dapat diisi dengan nilai konstan untuk membuat semua iterables memiliki panjang yang sama. Ini dilakukan oleh
Kasus tepi. Dengan satu argumen iterable, kembalikan iterator 1-tupel. Tanpa argumen, ia mengembalikan iterator kosong
Tip dan trik
Urutan evaluasi iterables dari kiri ke kanan dijamin. Hal ini memungkinkan idiom untuk mengelompokkan seri data ke dalam grup dengan panjang n menggunakan def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 17. Ini mengulangi iterator yang sama def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 18 kali sehingga setiap output tuple memiliki hasil def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 18 panggilan ke iterator. Ini memiliki efek membagi input menjadi potongan-potongan panjang n
bersama dengan operator def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 _21 dapat digunakan untuk membuka zip daftar
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') _0
Berubah di versi 3. 10. Menambahkan def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 22 argumen.
__import__(name , globals=None , locals=None , fromlist=() , level=0)Note
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 menugaskan ke def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 26) untuk mengubah semantik pernyataan def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 24, tetapi melakukan hal itu sangat tidak disarankan karena biasanya lebih mudah menggunakan kait impor (lihat PEP 302) untuk mencapai tujuan yang sama dan . Penggunaan langsung dari juga tidak disarankan karena mendukung
Fungsi mengimpor nama modul, berpotensi menggunakan global dan lokal yang diberikan untuk menentukan cara menginterpretasikan nama dalam konteks paket. fromlist memberikan nama objek atau submodul yang harus diimpor dari modul yang diberi nama. Implementasi standar tidak menggunakan argumen locals sama sekali dan menggunakan globalnya hanya untuk menentukan konteks paket dari pernyataan tersebut
level menentukan apakah akan menggunakan impor absolut atau relatif. def any(iterable): for element in iterable: if element: return True return False _92 (default) berarti hanya melakukan impor absolut. Nilai positif untuk level menunjukkan jumlah direktori induk untuk dicari relatif terhadap direktori pemanggilan modul (lihat PEP 328 untuk detailnya)
Ketika variabel nama berbentuk def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 33, biasanya, paket tingkat atas (nama sampai titik pertama) dikembalikan, bukan modul yang dinamai berdasarkan nama. Namun, ketika argumen fromlist yang tidak kosong diberikan, modul bernama by name dikembalikan
Misalnya, pernyataan def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 _34 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(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 35 menghasilkan panggilan ini
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') _2
Perhatikan bagaimana mengembalikan modul tingkat atas di sini karena ini adalah objek yang terikat pada sebuah nama dengan pernyataan
Di sisi lain, pernyataan def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 38 menghasilkan
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') _3
Di sini, modul def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 _39 dikembalikan dari. Dari objek ini, nama yang akan diimpor diambil dan ditetapkan ke namanya masing-masing
Jika Anda hanya ingin mengimpor modul (kemungkinan di dalam paket) dengan nama, gunakan
Berubah di versi 3. 3. Nilai negatif untuk level tidak lagi didukung (yang juga mengubah nilai default menjadi 0).
Berubah di versi 3. 9. Ketika opsi baris perintah atau sedang digunakan, variabel lingkungan sekarang diabaikan.
Catatan kaki
Perhatikan bahwa parser hanya menerima konvensi garis akhir gaya Unix. Jika Anda membaca kode dari file, pastikan untuk menggunakan mode konversi baris baru untuk mengonversi baris baru bergaya Windows atau Mac