Recursos do Python que eu nunca soube que existiam
Recentemente, tive um novo hobby - ler a documentação do Python apenas por diversĂŁo! Quando vocĂȘ lĂȘ em seu tempo livre, tende a notar informaçÔes interessantes que, de outra forma, perderia. EntĂŁo, aqui estĂĄ uma lista das "peças" que me fizeram dizer:
CERCA DE! VocĂȘ pode fazer isso em Python?
1. Atributos de funçÔes
Assim como vocĂȘ pode definir atributos em classes e objetos, vocĂȘ tambĂ©m pode definir atributos em funçÔes.
def func(x):
intermediate_var = x**2 + x + 1
if intermediate_var % 2:
y = intermediate_var ** 3
else:
y = intermediate_var **3 + 1
# setting attributes here
func.optional_return = intermediate_var
func.is_awesome = 'Yes, my function is awesome.'
return y
y = func(3)
print('Final answer is', y)
# Accessing function attributes
print('Show calculations -->', func.optional_return)
print('Is my function awesome? -->', func.is_awesome)
«optional_return» 10 «is_awesome» 11. 19 20. :
Final answer is 2197
Show calculations --> 13
Is my function awesome? --> Yes, my function is awesome.
, , , return . , , .
2. for-else
Python else for. else , break.
my_list = ['some', 'list', 'containing', 'five', 'elements']
min_len = 3
for element in my_list:
if len(element) < min_len:
print(f'Caught an element shorter than {min_len} letters')
break
else:
print(f'All elements at least {min_len} letters long')
All elements at least 3 letters long
, else for, if. . , break. , else ( for) , .
, , break. , , , , . :
my_list = ['some', 'list', 'containing', 'five', 'elements']
min_len = 3
no_break = True
for element in my_list:
if len(element) < min_len:
print(f'Caught an element shorter than {min_len} letters')
no_break = False
break
if no_break:
print(f'All elements at least {min_len} letters long')
, .
3. int
10000000 100000000 ( ?). , Python, , , Python .
Python : . , 1_000_000 .
a = 3250
b = 67_543_423_778
print(type(a))
print(type(b))
print(type(a)==type(b))
<class 'int'>
<class 'int'>
True
4. eval () exec ()
Python Python . eval() exec() (âevalâ ; âexecâ ).
a = 3
b = eval('a + 2')
print('b =', b)
exec('c = a ** 2')
print('c is', c)
b = 5
c is 9
eval() Python, b. 6 exec() Python .
. , 1000 _0, _1, .., _999 . , , .
, ( Python) eval/exec , , , , , . [âŠ] exec â Python, Python, , , â * *, exec .
â.
5. (Ellipsis)
( «âŠÂ») - Python, None, True, False .. -, , (, , ):
5.1.
pass, , , .
def some_function():
...
def another_function():
pass
5.2. NONE
None , . None . .
# calculate nth odd number
def nth_odd(n):
if isinstance(n, int):
return 2 * n - 1
else:
return None
# calculate the original n of nth odd number
def original_num(m=...):
if m is ...:
print('This function needs some input')
elif m is None:
print('Non integer input provided to nth_odd() function')
elif isinstance(m, int):
if m % 2:
print(f'{m} is {int((m + 1)/2)}th odd number')
else:
print(f'{m} is not an odd number')
original_num()
a = nth_odd(n='some string')
original_num(a)
b = nth_odd(5)
original_num(b)
original_num(16)
nth_odd() n- , c n. original_num() n, n- . None â original_num(), m. :
This function needs some input
Non integer input provided to nth_odd() function
9 is 5th odd number
16 is not an odd number
5.3. NumPy
NumPy . :
import numpy as np
a = np.arange(16).reshape(2,2,2,2)
print(a[..., 0].flatten())
print(a[:, :, :, 0].flatten())
[ 0 2 4 6 8 10 12 14]
[ 0 2 4 6 8 10 12 14]
, ââŠâ , â:â, .
Ao contrĂĄrio de None (cujo valor booleano Ă© False), o valor booleano das reticĂȘncias Ă© True.
TL; DR
EntĂŁo, descobri os seguintes recursos interessantes.
Atributos de função: atribuição de atributos a funçÔes e também a objetos.
Loop For-else: Rastreia se o loop foi executado sem uma instrução break.
Os delimitadores para int: 32_534_478 sĂŁo int.
eval () e exec (): lĂȘ as linhas como cĂłdigo Python e executa-o.
ReticĂȘncias: uma constante interna genĂ©rica.
Palavras de despedida
Python nĂŁo Ă© apenas uma linguagem Ăștil, mas tambĂ©m muito interessante. Estamos todos ocupados com nossas vidas, mas isso nĂŁo interfere no aprendizado do idioma por si sĂł. Gostaria de saber mais sobre os Ovos de PĂĄscoa que vocĂȘ possa encontrar.