Python2.7:在另一个程序/绑定中使用类的函数

2024-09-27 17:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个类(“Classname”),它除其他外,还具有以下功能:

def price(self): return self.price
def number(self): return self.number

我在这个类中还有另外一个函数,我想做如下工作:对于类中的每个对象,乘法自行定价由自身编号,并将其总和添加到要在程序中使用的变量中。你知道吗

def total(self,price,number):
   tot = 0
   for i in Classname:
       price = price(self)
       number = number(self)
       objvalue = price * number
       total += objvalue
   return total

在使用Classname函数的程序中,我很难使用类中定义的“total”函数。我只想让程序中定义的calcTotal函数返回类中total函数定义的“total”值。你知道吗

我试过:

def calcTotal:
    totalhere = Classname.total()

它回来了

"unbound method sumInventory() must be called with Classname instance as first argument (got nothing instead)"

所以我试着

totalhere = Classname.total(Classname)

它回来了

"unbound method sumInventory() must be called with Classname instance as first argument (got type instance instead.)"

我不确定如何绑定该方法以返回我希望它返回的内容。你知道吗


Tags: instance函数self程序numberreturn定义def
1条回答
网友
1楼 · 发布于 2024-09-27 17:37:22

从“for each individual object within the class”的发音来看,似乎你把类和容器混淆了。类本身并不是所有实例的容器。你知道吗

我想你可能想用两个不同的类,像这样。。。你知道吗

class Order(object):

    def __init__(self):
        self._items = []

    def add_item(self, item):
        self._items.append(item)

    def get_total_price(self):
        total = 0
        for item in self._items:
            total += item.price() * item.quantity()
        return total


class OrderItem(object):

    def __init__(self, price, quantity):
        self._price = price
        self._quantity = quantity

    def price(self):
        return self._price

    def quantity(self):
        return self._quantity

…然后你可以这样做。。。你知道吗

>>> o = Order()
>>> o.add_item(OrderItem(1.99, 2))
>>> o.add_item(OrderItem(0.99, 5))
>>> print o.get_total_price()
8.93

相关问题 更多 >

    热门问题