Pirate X
Pirate X

Reputation: 3095

Calling instance method of class from another another containing only self

class Cust(object):

    def __init__(self,cust_id,cust_day,cust_amt):
        self.id=cust_id
        self.total=0
        self.days=[cust_day]
        self.amounts=[cust_amt]


    def add_Purchases(self,day,amount):
        self.amounts.append(amount)
        self.days.append(day)
        print("add Purchase Executed for ",self.id,self.amounts)
        print(self.get_Total_Sales())

    def get_Total_Sales(self):
        total = sum(self.amounts)
        return total


class DB(object):

    def __init__(self,filedir):
        self.dir=filedir
        self.DB_cust={}
        self.createDatabase(filedir)    

    def importFile(self,file):
        file.readline() 
        for line in file:
            val=line.split(",") 

            customerID=data[0]
            if customerID in self.DB_cust:
                self.DB_cust[customerID].add_Purchases(val[2],float(val[3]))
            else:
                self.DB_cust[customerID]=Cust(val[0],val[1],val[2],float(val[3]))

I am trying to get the ID for maximum value of total. I call get_total_sales() from the instance method in DB class get_Max_ID()

def get_Max_ID(self):
    print("Max Sale ID here")
    Cust.get_Total_Sales()   

This obviously results in

TypeError: get_Total_Sales() missing 1 required positional argument: 'self'

If I pass self through get_Max_ID. It would pass the self of DB and not Cust. I am not sure how to pass the self of Cust whilst calling it from DB class.

Clarification - The get_Total_Sales() gets the total for each customer but I am trying to get maximum value of total out of all the customer instances. (I have not written that part of code which draws maximum total)

Upvotes: 0

Views: 176

Answers (1)

walnut
walnut

Reputation: 22152

Going by what OP says they want to do in the question comments, they probably want something like:

max([cust.get_Total_Sales() for id, cust in self.DB_cust.items()])

It will iterate over the dictionary of customers, and for each pair key/value pair (id and cust) will call and return that Cust's get_Total_Sales().

Then max will take all the individual results from the generated list of values and return only the maximum value.

As asked in the comment, although I see no reason not to use a comprehension:

results = []
for id, cust in self.DB_cust.items():
    results.append(cust.get_Total_Sales())
return max(results)

Upvotes: 1

Related Questions