2017-12-02 91 views
0

我是一個非常非常新的程序員,我不熟悉如何爲這個類設置打印方法。我該如何爲我的班級設置打印方法?感謝任何事情!如何爲我的課程發送打印方法?

class travelItem : 

    def __init__(self, itemID, itemName, itemCount) : 
     self.id = itemID 
     self.name = itemName 
     self.itemCount = itemCount 
     self.transactions = [] 

    def getID(self) : 
     return(self, id) 

    def getName(self) : 
     return(self.name) 

    def setName(self, newName) : 
     self.name = newName 

    def getAvailableStart(self): 
     return(self.AvailableStart) 

    def appendTransaction(self, num) : 
     self.transactions.append(num) 

    def getTransactions(self) : 
     return(self.transactions) 

    def getReservations(self) : 
     Additions = 0 
     for num in self.transactions : 
      if (num > 0) : 
       Additions = Additions + num 
     return(Additions) 

    def getCancellations(self) : 
     Subtractions = 0 
     for num in self.transactions : 
      if (num < 0) : 
       Subtractions = Subtractions + num 
     return(Subtractions) 

    def getAvailableEnd(self) : 
     total = self.AvailableStart 
     for num in self.transactions : 
      total = total + num 
     return(total) 
+0

創建['__str__'](https://docs.python.org/3/reference/datamodel.html#object.__str__ )方法 – excaza

+0

此外,[getters和setter在Python中一般被認爲是unidiomatic](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) 。 –

回答

0

請記住,一個方法被調用的類的實例,因此,如果你的意思是創建只打印一類你一個真實的方法可以寫類似

class Foo(object): 
    def print_me(self): 
     print(self) 

foo_instance= Foo() 
foo_instance.print_me() 

但它聽起來像你想定製打印的輸出()。這就是內置方法__str__的用途,所以試試這個。

class Foo(object): 
    def __str__(self): 
     # remember to coerce everything returned to a string please! 
     return str(self.some_attribute_of_this_foo_instance) 

從代碼中一個很好的例子可能是

... 
    def __str__(self): 
     return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions' 
0

必須使用__str__特殊方法:

class travelItem: 

    ... 
    def __str__(self): 
     return "a string that describe the data I want printed when print(instance of class) is called" 
相關問題