Extraño comportamiento
Publicado por Ernesto (2 intervenciones) el 13/09/2016 06:13:55
Por un error encontré un extraño comportamiento de Python. En este código:
yo esperaría que me diera un error por haber usado una variable no declarada yy en el método sumar. Sin embargo lo que hace es tomar la variable yy del main.
Moraleja: cuidado con usar nombres iguales de variables aunque parezcan estar en scopes distintos.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import numpy as np
class Prueba(object):
dura = 0
def __init__(self, yy):
print("Se inicializa")
self.n = yy
def suma(self):
Prueba.dura += 1
self.cf = np.array([[yy[0]], [yy[1]], [yy[2]]])
def resta(self):
Prueba.dura -= 1
def muestra(self):
print("dura: ", Prueba.dura)
# main ====================
yy = [1, 2, 3]
test1 = Prueba(1)
test2 = Prueba(2)
test1.suma()
yy = [4, 5, 6]
test2.suma()
test3 = Prueba(3)
test3.suma()
test3.muestra()
test1.muestra()
print(test1.cf)
print(test2.cf)
print(test3.cf)
yo esperaría que me diera un error por haber usado una variable no declarada yy en el método sumar. Sin embargo lo que hace es tomar la variable yy del main.
Moraleja: cuidado con usar nombres iguales de variables aunque parezcan estar en scopes distintos.
Valora esta pregunta


0