How to print out an int value in a class?

I am currently learning to create a class in python. I put in an int value in and it doesn't seem to print out the int value at all. Is there something I am doing wrong? This is my current code:

class Cars:
    def __init__ (self, model, Type, price):
        self.model  = 'Model:'+ model
        self.Type= 'Type:'+ Type
        self.price= price

    def fullname(self):
        return '{} {}'.format(self.model, self.Type)

    def Price(self):
        return 'Price:'.format(self.price)


car_1= Cars('CLA','Coupe', 34000)
car_2= Cars('GLA','SUV', 38000)

print(Cars.fullname(car_1))
print(car_1.Price())
print(car_2.fullname())
print(car_2.Price())

Output:

Model:CLA Type:Coupe
Price:
Model:GLA Type:SUV
Price:

I want to print out the price value under Price.

If there is anyone that can help, I would appreciate it. If there is a link to a similar question, please link if you can. Thank you.

Upvotes: 0

Views: 1145

Answers (1)

Devendra Lattu
Devendra Lattu

Reputation: 2802

You missed the {}. See https://docs.python.org/2/library/string.html#string.Formatter

def Price(self):
    return 'Price: {}'.format(self.price)

Moreover, you are naming a method (Price) very similar to a member (price).

  • If you want to tell the class to print the value, you should call the method something like printPrice. It's good practice to name methods by something that describes an action.
  • If you just want to get the member, use <object>.<member>.
  • If you really need to do something with the member before returning it, that is, you want to hide the inner workings of the class to the outside, then use Properties or Descriptors. But that's more advanced and should only be use if really needed.

Upvotes: 1

Related Questions