簡體   English   中英

如何在一個類中打印出一個int值?

[英]How to print out an int value in a class?

我目前正在學習在python中創建一個類。 我輸入一個int值,它似乎根本沒有打印出int值。 我做錯什么了嗎? 這是我當前的代碼:

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())

輸出:

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

我想在Price下打印出價格值。

如果有人可以提供幫助,我將不勝感激。 如果有類似問題的鏈接,請盡可能鏈接。 謝謝。

您錯過了{} 參見https://docs.python.org/2/library/string.html#string.Formatter

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

此外,您正在命名一個與成員( price )非常相似的方法( Price )。

  • 如果要告訴類打印值,則應調用諸如printPrice之類的方法。 最好用描述動作的名稱來命名方法。
  • 如果只想獲取成員,請使用<object>.<member>
  • 如果確實需要在返回成員之前對成員進行某些操作,即要將類的內部工作隱藏到外部,然后使用Properties或Descriptors 但這是更高級的,只有在真正需要時才應使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM