2017-12-02 5 views
0

私は非常に新しいプログラマーです。私はこのクラスのために印刷メソッドを設定する方法が不明で、クラスが新しくなっています。ここで私のクラスの印刷方法を設定するにはどうすればいいですか?何かありがとう!あなただけのクラスあなたを印刷し、真のメソッドを作成することを意味するので、もし、クラスの印刷方法をどのように送付するのですか?

class travelItem: 

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

を作成される可能性があります)メソッド – excaza

+0

また、[ゲッターとセッターは一般的にPythonでは単体と見なされます](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) 。 –

答えて

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__特別なメソッドを使用する必要があります。

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

foo_instance= Foo() 
foo_instance.print_me() 

でも、print()の出力をカスタマイズしたいと思うようです。それは方法__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) 

あなたのコードからの良い例は、[ `__str__`](https://docs.python.org/3/reference/datamodel.html#object.__str__を

... 
    def __str__(self): 
     return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions' 
関連する問題