10.6. Operator Builtin¶
abs
bool
complex
del
delattr
dir
divmod
float
getattr
hash
hex
int
iter
len
next
oct
pow
reversed
round
setattr
10.6.1. About¶
Function |
Method |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10.6.2. Length¶
>>> data = [1, 2, 3]
>>>
>>> len(data)
3
>>>
>>> data.__len__()
3
This is because len(data)
calls data.__len__()
.
>>> class Astronaut:
... pass
...
>>>
>>> a = Astronaut()
>>>
>>> len(a)
Traceback (most recent call last):
TypeError: object of type 'Astronaut' has no len()
>>> class Astronaut:
... def __len__(self):
... return 69
>>>
>>>
>>> a = Astronaut()
>>>
>>> len(a)
69
10.6.3. Float¶
>>> class Astronaut:
... pass
...
>>>
>>> a = Astronaut()
>>>
>>> float(a)
Traceback (most recent call last):
TypeError: float() argument must be a string or a real number, not 'Astronaut'
>>> class Astronaut:
... def __float__(self):
... return 13.37
...
>>>
>>> a = Astronaut()
>>>
>>> float(a)
13.37
10.6.4. Abs¶
>>> from math import sqrt
>>> from dataclasses import dataclass
>>>
>>>
>>> @dataclass
... class Vector:
... x: int = 0
... y: int = 0
...
... def __abs__(self):
... return sqrt(self.x**2 + self.y**2)
>>>
>>>
>>> abs(Vector(x=3, y=4))
5.0
10.6.5. Round¶
>>> pi = 3.1415
>>>
>>> type(pi)
<class 'float'>
>>>
>>> round(pi, 2)
3.14
>>>
>>> float.__round__(pi, 2)
3.14
10.6.6. Use Case - 0x01¶
>>> class Astronaut:
... def __float__(self) -> float:
... return 1961.0
...
... def __int__(self) -> int:
... return 1969
...
... def __len__(self) -> int:
... return 170
...
... def __str__(self) -> str:
... return 'My name... José Jiménez'
...
... def __repr__(self) -> str:
... return f'Astronaut()'
>>>
>>>
>>> astro = Astronaut()
>>>
>>> float(astro)
1961.0
>>>
>>> int(astro)
1969
>>>
>>> len(astro)
170
>>>
>>> repr(astro)
'Astronaut()'
>>>
>>> str(astro)
'My name... José Jiménez'
>>>
>>> print(astro)
My name... José Jiménez