Las gemas ocultas de Python

Funciones de Python que nunca supe que existían

Recientemente, tuve un nuevo pasatiempo: ¡leer la documentación de Python solo por diversión! Cuando lee en su tiempo libre, tiende a notar curiosidades interesantes que de otra manera se perdería. Entonces, aquí hay una lista de las "piezas" que me hicieron decir:





¡ACERCA DE! ¿Puedes hacerlo en Python?





1. Atributos de funciones

Al igual que puede establecer los atributos de clases y objetos, también puede establecer los atributos de funciones.





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]





, ‘…’ ,   ‘:’, .





A diferencia de None (cuyo valor booleano es False), el valor booleano de la elipsis es Verdadero.





TL; DR





Entonces, descubrí las siguientes características interesantes.





Atributos de función: Asignación de atributos tanto a funciones como a objetos.





Bucle For-else: Seguimiento de si el bucle se ejecutó sin una declaración de interrupción.





Los delimitadores para int: 32_534_478 son int.





eval () y exec (): lee líneas como código Python y ejecútalo.





Puntos suspensivos: una constante incorporada genérica.





Palabras de despedida

Python no solo es un lenguaje útil, sino también realmente interesante. Todos estamos ocupados con nuestras vidas, pero esto no interfiere con el aprendizaje del idioma por sí mismo. Me gustaría saber más sobre los huevos de Pascua que podrías encontrar.








All Articles