0

Me very very new programmer, I'm new to classes and not sure how to set up a print method for this class. How do I go about setting up a print method for my class here? Thanks for anything!

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)   
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
TeemoMain
  • 105
  • 1
  • 1
  • 8
  • Create a [`__str__`](https://docs.python.org/3/reference/datamodel.html#object.__str__) method for your object – sco1 Dec 02 '17 at 21:43
  • Also, [getters and setters are general considered unidiomatic in Python](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters). – Christian Dean Dec 02 '17 at 21:45

2 Answers2

0

You must use a __str__ special method:

class travelItem:

    ...
    def __str__(self):
        return "a string that describe the data I want printed when print(instance of class) is called"
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

Remember that a method is called on an instance of a class, so if you mean to create a true method that just prints a class you can write something like

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

foo_instance= Foo()
foo_instance.print_me()

But it sounds like you want to customize the output of print(). That is what the built in method __str__ is for, so try this.

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

a good example from your code might be

...
    def __str__(self):
        return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions'
Vincent Buscarello
  • 395
  • 2
  • 7
  • 19