type() et help() : introspection
En python, tout est objet.
Le type des objets est fixe.
Un même nom peut désigner tour à tour des objets de types différents : pas de « déclaration des variables ».
Comment s’y retrouver ?
Qui es-tu ?
[1]:
# type() nous indique le type d'un objet
print(type(2))
print(type(3.14))
print(type('toto'))
<class 'int'>
<class 'float'>
<class 'str'>
[2]:
type(2) == int
[2]:
True
[3]:
# Quel est le type de 'int' ?
print(type(int))
<class 'type'>
[4]:
# Quel est le type de 'type' ?
print(type(type(int)))
<class 'type'>
Que fais-tu ?
Plus que le type d’un objet, on s’intéressera à ce qu’il sait faire.
[5]:
help(2)
Help on int object:
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
| Return a pair of integers, whose ratio is exactly equal to the original int
| and with a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length, byteorder, *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
De même pour les fonctions.
[6]:
def add(x, y):
"additionne x et y"
result = x + y
return result
[7]:
print(type(add))
<class 'function'>
[8]:
help(add)
Help on function add in module __main__:
add(x, y)
additionne x et y
[9]:
# max() est une fonction 'builtin'
help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
Qui est là ?
Pour une information plus “brute” sur l’objet : dir()
et vars()
[10]:
# une list de string regroupant tous les noms (attribut/méthode) accessibles dans la classe int
dir(int)
[10]:
['__abs__',
'__add__',
'__and__',
'__bool__',
'__ceil__',
'__class__',
'__delattr__',
'__dir__',
'__divmod__',
'__doc__',
'__eq__',
'__float__',
'__floor__',
'__floordiv__',
'__format__',
'__ge__',
'__getattribute__',
'__getnewargs__',
'__gt__',
'__hash__',
'__index__',
'__init__',
'__init_subclass__',
'__int__',
'__invert__',
'__le__',
'__lshift__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__neg__',
'__new__',
'__or__',
'__pos__',
'__pow__',
'__radd__',
'__rand__',
'__rdivmod__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rfloordiv__',
'__rlshift__',
'__rmod__',
'__rmul__',
'__ror__',
'__round__',
'__rpow__',
'__rrshift__',
'__rshift__',
'__rsub__',
'__rtruediv__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__truediv__',
'__trunc__',
'__xor__',
'as_integer_ratio',
'bit_count',
'bit_length',
'conjugate',
'denominator',
'from_bytes',
'imag',
'numerator',
'real',
'to_bytes']
[11]:
# un dict de string:valeur regroupant tous les noms (attribut/méthode) accessibles dans la classe int et leurs valeurs
vars(int)
[11]:
mappingproxy({'__new__': <function int.__new__(*args, **kwargs)>,
'__repr__': <slot wrapper '__repr__' of 'int' objects>,
'__hash__': <slot wrapper '__hash__' of 'int' objects>,
'__getattribute__': <slot wrapper '__getattribute__' of 'int' objects>,
'__lt__': <slot wrapper '__lt__' of 'int' objects>,
'__le__': <slot wrapper '__le__' of 'int' objects>,
'__eq__': <slot wrapper '__eq__' of 'int' objects>,
'__ne__': <slot wrapper '__ne__' of 'int' objects>,
'__gt__': <slot wrapper '__gt__' of 'int' objects>,
'__ge__': <slot wrapper '__ge__' of 'int' objects>,
'__add__': <slot wrapper '__add__' of 'int' objects>,
'__radd__': <slot wrapper '__radd__' of 'int' objects>,
'__sub__': <slot wrapper '__sub__' of 'int' objects>,
'__rsub__': <slot wrapper '__rsub__' of 'int' objects>,
'__mul__': <slot wrapper '__mul__' of 'int' objects>,
'__rmul__': <slot wrapper '__rmul__' of 'int' objects>,
'__mod__': <slot wrapper '__mod__' of 'int' objects>,
'__rmod__': <slot wrapper '__rmod__' of 'int' objects>,
'__divmod__': <slot wrapper '__divmod__' of 'int' objects>,
'__rdivmod__': <slot wrapper '__rdivmod__' of 'int' objects>,
'__pow__': <slot wrapper '__pow__' of 'int' objects>,
'__rpow__': <slot wrapper '__rpow__' of 'int' objects>,
'__neg__': <slot wrapper '__neg__' of 'int' objects>,
'__pos__': <slot wrapper '__pos__' of 'int' objects>,
'__abs__': <slot wrapper '__abs__' of 'int' objects>,
'__bool__': <slot wrapper '__bool__' of 'int' objects>,
'__invert__': <slot wrapper '__invert__' of 'int' objects>,
'__lshift__': <slot wrapper '__lshift__' of 'int' objects>,
'__rlshift__': <slot wrapper '__rlshift__' of 'int' objects>,
'__rshift__': <slot wrapper '__rshift__' of 'int' objects>,
'__rrshift__': <slot wrapper '__rrshift__' of 'int' objects>,
'__and__': <slot wrapper '__and__' of 'int' objects>,
'__rand__': <slot wrapper '__rand__' of 'int' objects>,
'__xor__': <slot wrapper '__xor__' of 'int' objects>,
'__rxor__': <slot wrapper '__rxor__' of 'int' objects>,
'__or__': <slot wrapper '__or__' of 'int' objects>,
'__ror__': <slot wrapper '__ror__' of 'int' objects>,
'__int__': <slot wrapper '__int__' of 'int' objects>,
'__float__': <slot wrapper '__float__' of 'int' objects>,
'__floordiv__': <slot wrapper '__floordiv__' of 'int' objects>,
'__rfloordiv__': <slot wrapper '__rfloordiv__' of 'int' objects>,
'__truediv__': <slot wrapper '__truediv__' of 'int' objects>,
'__rtruediv__': <slot wrapper '__rtruediv__' of 'int' objects>,
'__index__': <slot wrapper '__index__' of 'int' objects>,
'conjugate': <method 'conjugate' of 'int' objects>,
'bit_length': <method 'bit_length' of 'int' objects>,
'bit_count': <method 'bit_count' of 'int' objects>,
'to_bytes': <method 'to_bytes' of 'int' objects>,
'from_bytes': <method 'from_bytes' of 'int' objects>,
'as_integer_ratio': <method 'as_integer_ratio' of 'int' objects>,
'__trunc__': <method '__trunc__' of 'int' objects>,
'__floor__': <method '__floor__' of 'int' objects>,
'__ceil__': <method '__ceil__' of 'int' objects>,
'__round__': <method '__round__' of 'int' objects>,
'__getnewargs__': <method '__getnewargs__' of 'int' objects>,
'__format__': <method '__format__' of 'int' objects>,
'__sizeof__': <method '__sizeof__' of 'int' objects>,
'real': <attribute 'real' of 'int' objects>,
'imag': <attribute 'imag' of 'int' objects>,
'numerator': <attribute 'numerator' of 'int' objects>,
'denominator': <attribute 'denominator' of 'int' objects>,
'__doc__': "int([x]) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given. If x is a number, return x.__int__(). For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base. The literal can be preceded by '+' or '-' and be surrounded\nby whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4"})
[12]:
# dir() et vars() sans argument sont aussi très utiles
help(dir)
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
Exercice
``max()`` est fournie par défaut (builtin), il y en a d’autres.
A quoi sert la seule fonction “builtin” qui commence “b” et finie par “n” ?
Indices :
dir()
nous donne les noms utilisé actuellementhelp(max)
nous dit d’où vient cette fonctiondir([truc])
nous donne le contenu detruc