Timothy Lombard
Timothy Lombard

Reputation: 967

Can I call a dict of python objects from with a method of another class?

I've created a class called Emp has attributes like employee number, department number, employee type etc. I've used this class to populate a dictionary called emp_dict.

I've done a similar thing for Dept with details of the department, now I want to create a method in the department class to measure the number contractors in this class but do do this I reference the emp_dict.

class Dept():
    def __init__(self,deptno, deptname):
        self.deptno = deptno
    def contractor_count(self,qtr,emp_dict): 
        contractor_count = 0
        if qtr in ['FY14Q1A','FY14Q2A','FY14Q3A','FY14Q4A',\
               'FY15Q1A','FY15Q2A','FY15Q3A','FY15Q4A',\
               'FY16Q1A','FY16Q2A','FY16Q3A','FY16Q4A',\
               'FY17Q1A','FY17Q2A','FY17Q3A','FY17Q4A']:
            for worker in self.allo[qtr].keys():
                if emp_dict[worker].emptype != "R" :
                    contractor_count_= 1
        return contractor_count  

When I tried using the count_contractor method it returns the initial value: 0 Should I be using another approach?

Upvotes: 2

Views: 58

Answers (2)

Tsangares
Tsangares

Reputation: 825

It seems like you have a spelling error, and hit _ instead of +:

your code should be:

class Dept():
def __init__(self,deptno, deptname):
    self.deptno = deptno
def contractor_count(self,qtr,emp_dict): 
    contractor_count = 0
    if qtr in ['FY14Q1A','FY14Q2A','FY14Q3A','FY14Q4A',\
           'FY15Q1A','FY15Q2A','FY15Q3A','FY15Q4A',\
           'FY16Q1A','FY16Q2A','FY16Q3A','FY16Q4A',\
           'FY17Q1A','FY17Q2A','FY17Q3A','FY17Q4A']:
        for worker in self.allo[qtr].keys():
            if emp_dict[worker].emptype != "R" :
                contractor_count+= 1
    return contractor_count  

The correction for the line: contractor_count+= 1

Upvotes: 0

wim
wim

Reputation: 362647

The contractor_count variable is never touched again. You have:

contractor_count_= 1

Did you mean this?

contractor_count += 1

I would also recommend using a variable name that is different from the method name, to avoid possible confusion.

Upvotes: 2

Related Questions