Builtin – Built-in functions and exceptions
All built-in functions and exceptions are described here. They are also available through the builtins module.
Functions
- abs()
Return the absolute value of a number. The argument may be an integer or a floating-point number. If the argument is a complex number, its magnitude is returned.
- all()
Return True if all elements of the iterable are true (or if the iterable is empty).
Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
- any()
Return True if any element of the iterable is true. If the iterable is empty, return False.
Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
- bin()
Convert an integer to a binary string prefixed with “0b”.
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
- class bool
Convert the given argument to a Boolean. If no argument is given, return False.
>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(None)
False
- class bytearray
Return a new bytes array. The bytearray class is a mutable sequence containing integers in the range 0 <= x < 256.
>>>bytearray()
bytearray(b'')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('mpython')
bytearray(b'mpython')
>>>
- class bytes
The bytes function returns a new bytes object, which is an immutable sequence of integers in the range 0 <= x < 256. It is the immutable version of bytearray. See CPython documentation: bytes
>>>a = bytes([1,2,3,4])
>>> a
b'\x01\x02\x03\x04'
>>> type(a)
<class 'bytes'>
>>>
>>> a = bytes('hello')
>>>
>>> a
b'hello'
>>> type(a)
<class 'bytes'>
>>>
- callable()
Check whether an object is callable. If it returns True, the object might still fail when called; but if it returns False, calling the object will never succeed.
>>>callable(0)
False
>>> callable("mpython")
False
>>> def add(a, b):
... return a + b
...
>>> callable(add) # function returns True
True
>>> class A: # class
... def method(self):
... return 0
...
>>> callable(A) # class returns True
True
>>> a = A()
>>> callable(a) # __call__ not implemented, returns False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # __call__ implemented, returns True
True
- chr()
Return the string representation of a character whose Unicode code point is the integer i.
>>>chr(0x30)
'0'
>>> chr(97)
'a'
>>> chr(8364)
'\u20ac'
- @classmethod
Convert a method into a class method.
A class method receives the class as its first argument, just like an instance method receives the instance as its first argument. Use the following idiom to declare a class method:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The form @classmethod is called a decorator for the function. A class method can be called either on the class (e.g., C.f()) or on an instance (e.g., C().f()). Instances of other classes are ignored. If the class method is called on a derived class, the derived class object is passed as the implied first argument.
- compile(source, filename, mode[, flags[, dont_inherit]])
Compile a string into bytecode. For details, see CPython documentation: compile
>>>str = "for i in range(0,10): print(i)"
>>> c = compile(str,'','exec') # compile to a code object
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
- class complex([real[, imag]])
Return the complex number real + imag*1j, or convert a string or number to a complex number. If the first parameter is a string, it is interpreted as a complex number, and the function must be called without a second parameter. The second parameter cannot be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero, and the constructor performs numeric conversion like int and float. If both arguments are omitted, return 0j.
>>>complex(1, 2)
(1 + 2j)
>>> complex(1) # number
(1 + 0j)
>>> complex("1") # treated as string
(1 + 0j)
# Note: there must be no spaces on either side of the "+" sign here, i.e., it cannot be written as "1 + 2j", it should be "1+2j", otherwise an error occurs
>>> complex("1+2j")
(1 + 2j)
- delattr(obj, name)
A function related to setattr(). 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 specified attribute, provided the object allows it. For example, delattr(x, ‘foobar’) is equivalent to del x.foobar.
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# triggers an error
print('z = ',point1.z)
- class dict(**kwarg)
- class dict(mapping, **kwarg)
- class dict(iterable, **kwarg)
**kwargs– keyword argumentsmapping– a container of elements.iterable– an iterable object.
The dict() function is used to create a dictionary.
>>>dict() # create an empty dictionary
{}
>>> dict(a='a', b='b', t='t') # pass keyword arguments
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # construct dictionary using map function
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # construct dictionary using an iterable
{'three': 3, 'two': 2, 'one': 1}
>>>
- dir(object)
When called without arguments, dir() returns the list of variables, methods, and defined types in the current scope; when called with an argument, it returns the list of attributes and methods of the argument. If the object has a __dir__() method, it will be called. If not, the method will collect information from the object as much as possible.
object– an object, variable, or type.
- divmod()
It takes two (non-complex) numbers as arguments and returns a pair consisting of their quotient and remainder when performing integer division. For mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is consistent with (a // b, a % b). For floating-point numbers, the result is (q, a % b), where q is usually math.floor(a / b) but may be less than that by 1. In any case, q * b + a % b is very close to a; if a % b is non-zero, its sign is the same as b, and 0 <= abs(a % b) < abs(b).
>>> divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(8, -2)
(-4, 0)
>>> divmod(3, 1.3)
(2.0, 0.4000001)
- enumerate(sequence[, start=0])
The enumerate() function combines a traversable data object (such as a list, tuple, or string) into an index sequence, listing both data and data subscripts simultaneously, generally used in for loops.
sequence– a sequence, iterator, or other object that supports iteration.start– the starting index position.
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
- eval(expression[, globals[, locals]])
The eval() function evaluates a string expression and returns the value of the expression.
expression– the expression.globals– variable scope, the global namespace; if provided, it must be a dictionary object.locals– variable scope, the local namespace; if provided, it can be any mapping object.
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
- exec(object[, globals[, locals]])
exec executes Python statements stored in a string or file. Compared to eval, exec can execute more complex Python code.
object: required parameter, representing the Python code to be executed. It must be a string or code object. If object is a string, it will first be parsed as a group of Python statements and then executed (unless a syntax error occurs). If object is a code object, it is simply executed.globals: optional parameter, representing the global namespace (storing global variables); if provided, it must be a dictionary object.locals: optional parameter, representing the current local namespace (storing local variables); if provided, it can be any mapping object. If this parameter is omitted, it will take the same value as globals.
>>>exec('print("Hello World")')
Hello World
# single-line statement string
>>> exec("print ('runoob.com')")
runoob.com
# multi-line statement string
>>> exec ("""for i in range(5):
... print ("iter time: %d" % i)
... """)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
- filter(function, iterable)
Filter a sequence, removing elements that do not meet the criteria, and return an iterator object. To convert it to a list, use list().
function– the test function.iterable– an iterable object.
Filter all odd numbers from a list:
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
- class float([x])
The float() function converts integers and strings to floating-point numbers.
>>>float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123') # string
123.0
- format(value[, format_spec])
The string formatting function str.format(), which enhances string formatting capabilities. The format function can accept an unlimited number of parameters, and positions can be out of order. The basic syntax uses {} and : to replace the old %. For more detailed syntax, see CPython Format String Syntax
>>>"{} {}".format("hello", "world") # no specified position, use default order
'hello world'
>>> "{0} {1}".format("hello", "world") # specify positions
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # specify positions
'world hello world
- class frozenset([iterable])
Return a frozen set. Once frozen, elements can no longer be added or removed from the set.
iterable– an iterable object, such as a list, dictionary, tuple, etc.
- getattr(object, name[, default])
Return the value of a named attribute of an object.
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # get the value of attribute bar
1
>>> getattr(a, 'bar2') # attribute bar2 does not exist, triggers exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # attribute bar2 does not exist, but a default value is set
- globals()
The globals() function returns all global variables at the current position as a dictionary.
- hasattr(object, name)
Determine whether an object has the corresponding attribute.
object– the object.name– a string, the attribute name.
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no')) # does not have this attribute
Output:
True
True
True
False
- hash(object)
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys when looking up elements in a dictionary. Numeric values of equal magnitude have the same hash value.
- help([object])
View detailed usage information for a function or module.
- hex(x)
Convert an integer to a lowercase hexadecimal string prefixed with “0x”.
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
- id([object])
Get the memory address of an object.
- input([prompt])
Receive data from standard input and return it as a string type.
- class int([x])
- class int(x, base=10)
Convert a string or number to an integer.
x– a string or number.base– the numeric base, defaults to decimal (10).- from_bytes(bytes, byteorder)
In MicroPython, the byteorder parameter must be a positional argument (this is compatible with CPython).
- to_bytes(size, byteorder)
In MicroPython, the byteorder parameter must be a positional argument (this is compatible with CPython).
Note
The optional signed keyword argument from CPython is not supported. MicroPython currently converts negative integers as signed and positive integers as unsigned.
- isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types, a TypeError exception is raised.
Differences between isinstance() and type()
type() does not consider subclasses as instances of the parent class; it does not account for inheritance.
isinstance() considers subclasses as instances of the parent class; it accounts for inheritance.
It is recommended to use isinstance() when checking whether two types are the same.
- issubclass(class, classinfo)
Return True if class is a subclass (direct, indirect, or virtual) of classinfo. classinfo can be a tuple of class objects, in which case each element of classinfo will be checked. In other cases, a TypeError exception is raised.
class A:
pass
class B(A):
pass
print(issubclass(B,A)) # returns True
- iter(object[, sentinel])
Generate an iterator.
object– a collection object that supports iteration.sentinel– if the second argument is passed, the object argument must be a callable object (such as a function). In this case, iter creates an iterator object that calls object each time its __next__() method is called.
>>>lst = [1, 2, 3]
>>> for i in iter(lst):
... print(i)
...
1
2
3
- len()
Return the length of an object (character, list, tuple, etc.) or the number of items.
>>>str = "runoob"
>>> len(str) # string length
6
>>> l = [1,2,3,4,5]
>>> len(l) # number of list elements
5
- class list
Convert a tuple or string to a list.
aTuple = (123, 'Google', 'baidu', 'Taobao')
list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World"
list2=list(str)
print ("List elements : ", list2)
Output:
List elements : [123, 'Google', 'Runoob', 'Taobao']
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
- locals()
Return all local variables at the current position as a dictionary.
>>>def runoob(arg): # two local variables: arg, z
... z = 1
... print (locals())
...
>>> runoob(4)
{'z': 1, 'arg': 4} # returns a dictionary of name/value pairs
>>>
- map(function, iterable, ...)
map() applies the provided function to each item of the specified sequence and returns an iterator that yields the results. If additional iterable 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.
>>>def square(x) : # calculate the square
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # calculate squares of each list element
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # use a lambda anonymous function
[1, 4, 9, 16, 25]
# provide two lists, add elements at the same positions
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
- max()
Return the largest item from the given arguments; the arguments can be a sequence.
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))
Output:
max(80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100
- class memoryview
Return a memory view object of the given argument. A memory view object wraps data that supports the buffer protocol, allowing Python code to access it without copying.
>>>v = memoryview(bytearray("abcefg"))
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memoryview>
>>> bytes(v[1:4)
b'bce'
>>>
- min()
Return the smallest item from the given arguments; the arguments can be a sequence.
print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))
Output:
min(80, 100, 1000) : 80
min(-20, 100, 400) : -20
min(-80, -20, -10) : -80
min(0, 100, -400) : -400
- next(iterator[, default])
Return the next item from the iterator. It retrieves the next element by calling the iterator’s __next__() method. If the iterator is exhausted, the given default is returned; if no default is provided, StopIteration is raised.
# First get the Iterator object:
it = iter([1, 2, 3, 4, 5])
# Loop:
while True:
try:
# Get the next value:
x = next(it)
print(x)
except StopIteration:
# Exit the loop when StopIteration is encountered
break
- class object
- oct()
Convert an integer to an octal string.
>>>oct(10)
'012'
>>> oct(20)
'024'
>>> oct(15)
'017'
>>>
- open()
The open() method opens a file and returns a file object. This function is needed whenever a file is processed. If the file cannot be opened, an OSError is raised. Note: when using open(), always ensure the file object is closed, i.e., call the close() method.
The common form of the open() function takes two arguments: the filename (file) and the mode:
open(file, mode='r')
mode is an optional string that specifies the mode in which the file is opened. The default is ‘r’, which means open for reading in text mode. Other common modes are: ‘w’ for writing (truncating the file if it already exists); ‘x’ for exclusive creation; ‘a’ for appending (on some Unix systems, all writes append to the end of the file regardless of the current file pointer position). Available modes are:
Mode |
Description |
‘r’ |
Open for reading (default) |
‘w’ |
Open for writing, truncating the file first |
‘x’ |
Open for exclusive creation, failing if the file already exists |
‘a’ |
Open for writing, appending to the end of the file if it exists |
‘a’ |
Open for writing, appending to the end of the file if it exists |
‘b’ |
Binary mode |
‘t’ |
Text mode (default) |
‘+’ |
Update the file on disk (read and write) |
The default mode is ‘r’ (open for reading text, same as ‘rt’). For binary writing, ‘w+b’ mode opens and truncates the file to 0 bytes; ‘r+b’ does not truncate.
- ord(c)
This is the inverse of chr(). It takes a string (Unicode character) as a parameter and returns the integer representing the corresponding Unicode code point.
>>>ord('a')
97
>>> ord('\u20ac')
8364
>>>
- pow(x, y[, z])
Return the value of x raised to the power of y.
print ("pow(100, 2) : ", pow(100, 2))
print ("pow(100, -2) : ", pow(100, -2))
print ("pow(2, 4) : ", pow(2, 4))
print ("pow(3, 0) : ", pow(3, 0))
Output:
pow(100, 2) : 10000
pow(100, -2) : 0.0001
pow(2, 4) : 16
pow(3, 0) : 1
- print(*objects, sep=' ', end='\n', file=sys.stdout)
Used for printing output, one of the most common functions.
objects: plural, indicating that multiple objects can be output at once. When outputting multiple objects, they need to be separated by commas.
sep: used to separate multiple objects; the default is a space.
end: used to set what to append at the end. The default is a newline character n, which can be replaced with another string.
file: the file object to write to.
>>> print(1)
1
>>> print("Hello World")
Hello World
>>> a = 1
>>> b = 'w3cschool'
>>> print(a,b)
1 w3cschool
>>> print("aaa""bbb")
aaabbb
>>> print("aaa","bbb")
aaa bbb
>>>
>>> print("www","w3cschool","cn",sep=".") # set the separator
www.w3cschool.cn
- @property
The property() function returns a property value in new-style classes. Using the property function as a decorator makes it easy to create read-only properties:
The getter, setter, and deleter methods of property can also be used as decorators:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
- range()
The range() function returns an iterable object (its type is an object), not a list type, so printing it will not print a list.
Function syntax:
range(stop)
range(start, stop[, step])
>>>range(5)
range(0, 5)
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0))
[]
>>>
With two or three arguments (the second form):
>>>list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(1, 0))
[]
>>>
>>>
- repr()
Return a string containing a printable representation of an object.
>>>s = 'baidu'
>>> repr(s)
"'baidu'"
>>> dict = {'baidu': 'baidu.com', 'google': 'google.com'}
>>> repr(dict)
"{'google': 'google.com', 'baidu': 'baidu.com'}"
>>>
- reversed(seq)
Return a reverse iterator.
# string
seqString = 'Runoob'
print(list(reversed(seqString)))
# tuple
seqTuple = ('R', 'u', 'n', 'o', 'o', 'b')
print(list(reversed(seqTuple)))
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
# list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
Output:
['b', 'o', 'o', 'n', 'u', 'R']
['b', 'o', 'o', 'n', 'u', 'R']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]
- round(x[, n])
Return the rounded value of a floating-point number x.
x- a numeric expression.
n- the number of decimal places to which x should be rounded; the default is 0.
print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
Output:
round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
- class set([iterable])
The set() function creates an unordered collection of unique elements, which can be used for membership testing, removing duplicates, and computing intersections, differences, unions, etc.
>>> x = set('runoob')
>>> y = set('google')
>>> x, y
({'b', 'u', 'n', 'o', 'r'}, {'e', 'l', 'g', 'o'}) # duplicates are removed
>>> x & y # intersection
{'o'}
>>> x | y # union
{'e', 'u', 'o', 'n', 'r', 'l', 'g', 'b'}
>>> x - y # difference
{'b', 'u', 'n', 'r'}
>
- setattr(object, name, value)
The setattr() function corresponds to getattr(). It is used to set the value of an attribute, which does not necessarily have to exist.
Assign a value to an existing attribute:
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # get the value of attribute bar
1
>>> setattr(a, 'bar', 5) # set the value of attribute bar
>>> a.bar
5
If the attribute does not exist, a new object attribute will be created and assigned a value:
>>>class A():
... name = "runoob"
...
>>> a = A()
>>> setattr(a, "age", 28)
>>> print(a.age)
28
>>>
- class slice
- sorted(iterable, *, key=None, reverse=False)
Sort all iterable objects.
iterable– an iterable object.key– mainly used for comparison; it takes only one parameter. The function’s parameter is taken from the iterable, specifying one element from the iterable to use for sorting.reverse– sorting rule; reverse = True for descending, reverse = False for ascending (default).
The simplest usage of sorted:
>>>sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5] # default is ascending
Use key for reverse sorting:
>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> result_list = sorted(example_list, key=lambda x: x*-1)
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
>>>
To perform reverse sorting, you can also pass the third argument reverse=True:
>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> sorted(example_list, reverse=True)
[7, 6, 5, 4, 3, 2, 1, 0]
- @staticmethod
Convert a method into a static method.
A static method does not receive an implicit first argument. To declare a static method, use this syntax:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
A static method can be called either on the class (e.g., C.f()) or on an instance (e.g., C().f()).
- class str
Convert an object to a str object.
>>>s = 'w3cschool'
>>> str(s)
'W3Cschool'
>>> dict = {'w3cschool': 'w3cschool', 'google': 'google.com'};
>>> str(dict)
"{'google': 'google.com', 'w3cschool': 'w3cschool.cn'}"
>>>
- sum(iterable[, start])
>>>sum([0,1,2])
3
>>> sum((2, 3, 4), 1) # sum the tuple then add 1
10
>>> sum([0,1,2,3,4], 2) # sum the list then add 2
12
- super()
The super() function is used to call a method of the parent (super) class.
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
b = B()
b.add(2) # 3
- class tuple
Convert a list to a tuple.
>>>list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
- type()
The type() function returns the type of an object when called with only the first argument, and returns a new type object when called with three arguments.
type(object)type(name, bases, dict)name– the name of the class.bases– a tuple of base classes.dict– a dictionary, the namespace variables defined within the class.
Hint
Differences between isinstance() and type()
type() does not consider subclasses as instances of the parent class; it does not account for inheritance.
isinstance() considers subclasses as instances of the parent class; it accounts for inheritance.
It is recommended to use isinstance() when checking whether two types are the same.
>>> type(1)
<type 'int'>
>>> type('runoob')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1
>>> type( x ) == int # check whether types are equal
True
# three arguments
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1)) # produce a new type X
>>> X
<class '__main__.X'>
Difference between type() and isinstance():
class A:
pass
s
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
- zip([iterable, ...])
The zip() function takes iterables as arguments, packs corresponding elements from each into tuples, and returns an object composed of these tuples. The advantage is that it saves a considerable amount of memory.
We can use list() to convert and output a list. If the iterables have different lengths, the returned list length matches the shortest object. Using the * operator, tuples can be unpacked into lists.
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # returns an object
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() converts to a list
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # number of elements matches the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> a1, a2 = zip(*zip(a,b)) # the reverse of zip, zip(*) can be understood as unpacking, returns a 2D matrix
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
Exceptions
- exception AssertionError
- exception AttributeError
- exception Exception
- exception ImportError
- exception IndexError
- exception KeyboardInterrupt
See CPython documentation:
KeyboardInterrupt. Also see the related content on Soft Bricking (boot failure).
- exception KeyError
- exception MemoryError
- exception NameError
- exception NotImplementedError
- exception OSError
See CPython documentation:
OSError. MicroPython does not implement theerrnoattribute; instead, it uses the standard way to access exception arguments:exc.args[0].
- exception RuntimeError
- exception StopIteration
- exception SyntaxError
- exception SystemExit
See CPython documentation:
SystemExit.On non-embedded ports (i.e., Windows and Unix), an unhandled SystemExit will exit the MicroPython process in a manner similar to CPython. On embedded ports, an unhandled SystemExit currently causes a soft reset of MicroPython.
- exception TypeError
See CPython documentation:
TypeError.
- exception ValueError
- exception ZeroDivisionError