Why does this strange result appear when printing the values defined in the class? (Python)

1

Well, I created this class (Car class), then set the values for each argument of that class. But when printing the variable with the already defined values, 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.

Just curious, I'd like to know why.

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

From now on I thank you for the collaboration of vcs, valew galera!

    
asked by anonymous 08.10.2017 / 18:08

1 answer

2

Let's look at your code step by step:

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

You have a class that models a car, this class has attributes: Template, color, and mpg (which I do not know what it 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 'Monza' values for model, 'brown' for color and '55' for mpg (which I still do not know what it is). In this way the variable 'car1' is an object , when you try to print an object you receive as a return the position of that object in the computer's memory.

<Car object at 0x7fa71d52fb10>

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

car1.display_car #Deve imprimir os atributos de seu carro.
    
08.10.2017 / 18:24