我如何为班级发送打印方法?

时间:2017-12-02 21:41:30

标签: python

我非常非常新的程序员,我是新手,不知道如何为这个类设置打印方法。我如何在这里为我的课程设置打印方法?谢谢!

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)   

2 个答案:

答案 0 :(得分:0)

您必须使用__str__特殊方法:

class travelItem:

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

答案 1 :(得分:0)

请记住,在类的实例上调用方法,因此如果您要创建一个只打印类的true方法,则可以编写类似

的内容。
int main() {

    string in;
    cin >> in;
    vector<int> y, b;
    y = Recurofnum(in, 0, b);
    for (const auto& i : y) { cout << y.at(i); }
    system("PAUSE");
}

但听起来你想要自定义print()的输出。这就是内置方法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)