Pq shows this strange result when printing the values defined in class ? (Python)

Asked

Viewed 31 times

1

Guys, I created this class (Car class), then defined the values for each argument of this class. Only when printing the variable with the values already defined, this appears:

#isso é o que aparece ao imprimir a variável car1
<Car object at 0x7fa71d52fb10>


class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg

  def display_car(self):
    print("This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

  def drive_car(self):
    self.condition = "used"

car1 = Car('Monza', 'marron', 55)
print(car1)#É ESSA variável que, ao ser imprimida, imprime aquele valor estranho.

only on the level of curiosity, I would like to know why this behavior.

NOTE:Remembering that I am a self-taught student in programming, so have a little more patience, ok?

Thanks in advance for the collaboration of you guys!

1 answer

2


Let’s take a step by step look at your code:

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg

You own a class that models a car, this class has the attributes: Model , color and mpg (which I don’t know what is)

  def display_car(self):
    print("This is a %s %s with %s MPG." % (self.color, self.model, 
str(self.mpg))

  def drive_car(self):
    self.condition = "used"

Your class also has methods that 'do' something with attributes.

car1 = Car('Monza', 'marron', 55)
print(car1)

When the car object is created, it receives the values 'Monza' for model, 'Marron' for color and '55' for mpg (which I still don’t know what it is). Thus the variable 'car1' is a object, when you try to print an object you get as return the position of that object in the memory of the computer.

<Car object at 0x7fa71d52fb10>

This is because an object is simply an object :D What do you mean ? An object by itself does nothing, it just receives its values and so it comes into being. To 'manipulate' the object and 'give life' it uses methods. That way if you wanted to print the values that were assigned to car1 you need to do this interaction through a method that by the way already exists in your code which is the display_car.

car1.display_car #Deve imprimir os atributos de seu carro.
  • your reply was SEN-SA-CIONAL, very clear and objective, thank you very much! , congratulations!!!

  • Thanks Eduardo , if you need us we are there :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.