I have a Python application running on a PC that needs to interface with an Arduino.
All communication is initiated by the PC; the Arduino should only respond.
Communications must exchange texts and values.
Help please, nothing works for me.
I have a Python application running on a PC that needs to interface with an Arduino.
All communication is initiated by the PC; the Arduino should only respond.
Communications must exchange texts and values.
Help please, nothing works for me.
I have two classes that for example purposes I'll call Entero
and Flotante
. I need a method for an object to change classes on its own, without the intervention of external code.
The desired result is illustrated by the following pseudo-code:
class Entero:
def __init__(self, valor: int):
self.valor = valor
def convertir_a_flotante(self):
self.valor = float(self.valor)
# Aqui cambiar la clase del objeto a Flotante.
class Flotante:
def __init__(self, valor: float):
self.valor = valor
def convertir_a_entero(self):
self.valor = int(self.valor)
# Aqui cambiar la clase del objeto a Entero.
a = Entero(1)
print(f"Type(a) = {type(a)}") => Type(a) = <class '__main__.Entero'>
a.convertir_a_flotante()
print(f"Type(a) = {type(a)}") => Type(a) = <class '__main__.Flotante'>
The idea is not to generate a new object, but to preserve the existing one, so that previous references to the object are still valid.
With CalumRakk's answer and Abulafia's comments, I made a second version to check that the mutated object is really of the new class, implementing the common method__str__
class Entero:
def __init__(self, valor: int):
self.valor = valor
def convertir_a_flotante(self):
self.valor = float(self.valor)
self.__class__=Flotante
def __str__(self):
return f"Entero {self.valor}"
class Flotante:
def __init__(self, valor: float):
self.valor = valor
def convertir_a_entero(self):
self.valor = int(self.valor)
self.__class__=Entero
def __str__(self):
return f"Flotante {self.valor}"
a = Entero(1)
print(a, type(a))
a.convertir_a_flotante()
print(a, type(a))
which produces:
Entero 1 <class '__main__.Entero'>
Flotante 1.0 <class '__main__.Flotante'>
Process finished with exit code 0
I have a base class Numero
and numerous specialized subclasses (decimal, float, times, lat/lon, etc). The base class and subclasses are instantiated from the string representation:
valor1 = NumeroEntero("10")
valor2 = NumeroDecimal("10.1")
valor3 = NumeroPosicion("40.423261°N 3.712594°W")
What I'm looking for is to be able to simply say
valor1 = Numero("10") => type(valor1) es NumeroEntero
valor2 = Numero("10.1") => type(valor2) es NumeroDecimal
valor3 = Numero("40.423261°N 3.712594°W") => type(valor3) es NumeroPosicion
and obtain as a result three objects of different subclasses.
This (illegal) code shows what I intend:
class Numero:
def __init__(self, valor: str):
if '.' in valor:
return NumeroDecimal(valor)
else:
return NumeroEntero(valor)
class NumeroEntero(Numero):
def __init__(self, valor: str):
self.valor = int(valor)
class NumeroDecimal(Numero):
def __init__(self, valor: str):
self.valor = float(valor)
var1 = Numero("10") => type(var1) == NumeroEntero
var2 = Numero("10.0") => type(var2) == NumeroDecimal
I could just write a function that receives the text, examines it and returns the appropriate object, but I find that inelegant.
Does anyone know a hack to solve it?
I understood that
import XXX
print(XXX.a)
Y
from XXX import a, b, c
print(a)
they were the same, and choosing one over the other was a matter of personal preference.
The thing is, I have this module servicio.py
that contains the mockup of a service that reads some data and keeps it in the variable var
.
Every time the service is called, var
it should be updated, which I simulate by adding 100 to it on each pass.
service.py
var = 1
def cambia():
global var
var += 100
print(f"cambia var = {var}")
From another module I want to call the service and then retrieve the value by directly accessing the variable var
.
Alternative 1
import servicio
print(id(servicio.var), servicio.var)
servicio.cambia()
print(id(servicio.var), servicio.var)
which produces:
9788992 1
cambia var = 101
9792192 101
Alternative 2
from servicio import var, cambia
print(id(var), var)
cambia()
print(id(var), var)
which produces:
9788992 1
cambia var = 101
9788992 1
Can someone explain the difference to me?
I have an application where I need to create many different classes. For each class I must write the __init__
, the setters and getters , the supporting functions like __repr__
and , __str__
and other bureaucratic minutiae.
Is there a shorter way to build a class?
I am new to the company and inherited this code which implements the traditional cat game, over a 3x3 matrix.
Now they ask me to transform it to an NxN game, and they told me that I had to refactor it to make it simpler.
What is code refactoring?
This is the code:
#include <stdio.h>
int main(){
char matriz[3][ 3], opc;
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++){
matriz[i][j]=' ';
printf(" %c", matriz[i][j]);
}
printf("\n");
}
int fila, col, ganador=0, turno=1;
//para jugador 1
do{
if(turno%2==1){
do{
scanf("%d", &fila);
scanf("%d", &col);
//ciclo para cuando el usuario ingrese coordenadas invalidas
if(matriz[fila][col] == 'x' || matriz[fila][col] == 'o' || fila > 2 || col > 2){
}
}while(matriz[fila][col] == 'x' || matriz[fila][col] == 'o' || fila > 2 || col > 2);
matriz[fila][col]='x';
for(i=0; i<3; i++){
for(j=0; j<3; j++){
printf(" %c", matriz[i][j]);
}
printf("\n");
}
turno++;
//para jugador dos
} else if(turno%2==0){
do{
scanf("%d", &fila);
scanf("%d", &col);
//ciclo para cuando el usuario ingrese coordenadas invalidas
if(matriz[fila][col] == 'x' || matriz[fila][col] == 'o' || fila > 2 || col > 2){
}
} while(matriz[fila][col] == 'x' || matriz[fila][col] == 'o' || fila > 2 || col > 2);
matriz[fila][col]='o';
for(i=0; i<3; i++){
for(j=0; j<3; j++){
printf(" %c", matriz[i][j]);
}
printf("\n");
}
turno++;
}
if(matriz[0][0] == 'x' && matriz[0][0] == matriz[0][1] && matriz[0][0] == matriz[0][2]
|| matriz[1][0] == 'x' && matriz[1][0] == matriz[1][1] && matriz[1][0] == matriz[1][2]
|| matriz[2][0] == 'x' && matriz[2][0] == matriz[2][1] && matriz[2][0] == matriz[2][2]
|| matriz[0][0] == 'x' && matriz[0][0] == matriz[1][0] && matriz[0][0] == matriz[2][0]
|| matriz[0][1] == 'x' && matriz[0][1] == matriz[1][1] && matriz[0][1] == matriz[2][1]
|| matriz[0][2] == 'x' && matriz[0][2] == matriz[1][2] && matriz[0][2] == matriz[2][2]
|| matriz[0][0] == 'x' && matriz[0][0] == matriz[1][1] && matriz[0][0] == matriz[2][2]
|| matriz[0][2] == 'x' && matriz[0][2] == matriz[1][1] && matriz[0][2] == matriz[2][0]){
ganador=1;
printf("1\n");
}
if(matriz[0][0] == 'o' && matriz[0][0] == matriz[0][1] && matriz[0][0] == matriz[0][2]
|| matriz[1][0] == 'o' && matriz[1][0] == matriz[1][1] && matriz[1][0] == matriz[1][2]
|| matriz[2][0] == 'o' && matriz[2][0] == matriz[2][1] && matriz[2][0] == matriz[2][2]
|| matriz[0][0] == 'o' && matriz[0][0] == matriz[1][0] && matriz[0][0] == matriz[2][0]
|| matriz[0][1] == 'o' && matriz[0][1] == matriz[1][1] && matriz[0][1] == matriz[2][1]
|| matriz[0][2] == 'o' && matriz[0][2] == matriz[1][2] && matriz[0][2] == matriz[2][2]
|| matriz[0][0] == 'o' && matriz[0][0] == matriz[1][1] && matriz[0][0] == matriz[2][2]
|| matriz[0][2] == 'o' && matriz[0][2] == matriz[1][1] && matriz[0][2] == matriz[2][0]){
ganador=1;
printf(" 2\n");
}
} while(ganador != 1);
return 0;
}
I have this program
a = 5
print("valor=", 5*a())
when executing it throws me this error:
Traceback (most recent call last):
File "/home/candid/PycharmProjects/scrapper2/scrapper.py", line 2, in <module>
print("valor=", 5*a())
TypeError: 'int' object is not callable
and I don't understand what I'm doing wrong.
What does the star operator * do in Python when used as an argument in functions like zip(*x)
or fcn(**k)
?
Linux (Mint Ulyana) comes with Python 2.7 and Python 3.8 installed by default, but not pip
.
The normal method for installing Python modules is via the Package Manager. Of course, not all modules are available or in their latest versions this way.
The utility pip
is available via the Package Manager, but can I use it to install modules and/or versions that are not available in the Package Manager without causing conflicts or inconsistencies?
I have a probability study program that does 10,000,000 iterations. In each iteration you have to apply some heavy formulas that include the calculation of the factorial, and it is taking a long time.
I have been told that I must apply memorization to reduce process times.
Could you tell me what it is and how I use it?
I'm looking for how to do file input/output in Python. I wrote the following code to read a list of names (one per line) from a file and write them to another file. If the name read matches a name given by the user, I add a text to it before recording it. The code works, but how could I improve it?
I want to use the with open(...)
for the input and output files, but I don't see how to put them in the same block, which means I have to temporarily store the names somewhere else.
def filter(txt, oldfile, newfile):
'''\
Lee una lista de nombres desde un archivo línea por línea hacía un archivo de salida.
Si la línea comienza con un nombre en particular, insertar una cadena de texto
detrás del nombre antes de añadirlo a la línea del archivo de salida.
'''
outfile = open(newfile, 'w')
with open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Realmente una gran persona!\n'
outfile.write(line)
outfile.close()
return # ¿Gano algo con agregar esto?
# Ingresar los nombres a revisar
text = input('Por favor, ingrese el nombre de una gran persona: ')
letsgo = filter(text, 'entrada.txt', 'salida.txt')