Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
¿Cómo llamar a una clase usando 3 funciones?

Me gustaría crear una clase de Python con 3 funciones.

  • La función 1 le pedirá al usuario que ingrese un número.
  • La función 2 le pedirá al usuario que ingrese otro número.
  • La función 3 multiplicará la función 1 * la función 2 y volverá al producto.

Aquí está el código que tengo hasta ahora:

 class Product: def __init__(self, x, y): self.x = x self.y = y def get_x(self): x = int(input('What is the first number?: ') def get_y(self): y = int(input('What is the second number?: ') def mult_XY(self): return x * y

Cuando trato de llamar a la clase, obtengo 'y' is not defined .

Intenté usar el siguiente código:

 num = Product(x, y) print(num.mult_XY)
over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

Parece que olvidó usar la palabra clave self en la definición de la función. Hay muchos errores en tu código. Creo que esta es la versión correcta de su código:

 class Product: def __init__(self, x, y): self.x = x self.y = y def get_x(self): self.x = int(input('What is the first number?: ')) def get_y(self): self.y = int(input('What is the second number?: ')) def mult_XY(self): return self.x * self.y

Y así es como deberías comprobar que funciona:

(Versión actualizada)

 x = 10 y = 5 num = Product(x, y) num.get_x() num.get_y() print(num.mult_XY())
over 4 years ago · Santiago Trujillo Report

0

Para hacer referencia a cualquier cosa almacenada en el objeto actual, debe usar self. como lo hizo en la función init para guardar originalmente los valores.

Ejemplo:

 class Product: def __init__(self, x, y): self.x = x self.y = y def get_x(self): self.x = int(input('What is the first number?: ')) def get_y(self): self.y = int(input('What is the second number?: ')) def mult_XY(self): return self.x * self.y
over 4 years ago · Santiago Trujillo Report

0

No estoy seguro de entenderlo correctamente, pero es posible que necesite "x" e "y" para ser las entradas dentro de la clase.

Si es así, use classmethod s:

 class Product: @classmethod def get_x(self): self.x = int(input('What is the first number?: ')) return self @classmethod def get_y(self): self.y = int(input('What is the second number?: ')) return self @classmethod def mult_XY(self): return self.x * self.y

Ex:

 >>> Product.get_x().get_y().mult_XY() What is the first number?: 3 What is the second number?: 4 12 >>>
over 4 years ago · Santiago Trujillo Report

0

Aquí hay una solución de trabajo. Compáralo con tu solución actual y detecta las diferencias. Después del siguiente fragmento de código, resaltaré los conceptos que necesita investigar para comprender mejor este programa.

Aquí hay una versión correcta de su código (nota: potencialmente hay más de una solución):

 class Product: def __init__(self): return def get_x(self): self.x = int(input('What is the first number?: ')) return self.x def get_y(self): self.y = int(input('What is the second number?: ')) return self.y def mult_XY(self): return self.x * self.y p = Product() x = p.get_x() y = p.get_y() result = p.mult_XY() print('RESULT of {} * {} = {}'.format(x, y, result))

¿Es esta la mejor respuesta? No. Dependiendo de las especificaciones de su programa, la estructura del código podría ser diferente.

Tiene lagunas de conocimiento sobre los siguientes conceptos:

  • Objetos y clases en Python
  • Funciones en Python
  • Variables y alcance en Python

Para comprender mejor, debe aprender más sobre los fundamentos de Python. Aquí hay un buen recurso para comenzar: https://python-textbok.readthedocs.io/en/1.0/Introduction.html

Después de leer eso, no solo podrá responder a esta pregunta, sino también establecer las bases para su conocimiento de programación. No te rindas y te deseo lo mejor.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!