如果语句仅为所有条件生成一个输出

时间:2017-05-11 03:07:42

标签: python django decorator

我在python中使用装饰器完成了多个聚合函数。

这些if条件仅为不同值的一个条件生成输出。

我尝试过改变位置,但它们总是产生相同的输出。

我做错了什么?

如何根据条件

中的要求使值不同

示例代码:

   # This class allows function addition, multiplication, division 
            etc.
class operable:
   def __init__(self, f):
        self.f = f
   def __call__(self, x):
        return self.f(x)

def op_to_function_op(op):
   def function_op(self, operand):
        def f(x):
            return op(self(x), operand(x))
        return operable(f)
   return function_op

 for name, op in [(name, getattr(operator, name)) for name in 
    dir(operator) if "__" in name]:
    try:
        op(1,2)
    except TypeError:
        pass
    else:
        setattr(operable, name, op_to_function_op(op))

 def allocate_service(ModelAdmin, request, queryset):
    platinum_customers = []
    silver_customers = []
    gold_customers = []
    non_customers = []
    message = ''


    for customer in queryset:



        @operable
        def getAge():
            age = 0

            if customer.Age == Customer.objects.get(Age = "60 +"):
                age = 0

            elif customer.Age == Customer.objects.get(Age = "36 - 59"):
                age = 1
            else:
                age = 2


        def getEducation():
            education = 0
            if customer.Education == Customer.objects.get(Education = 
                "Highschool and below"):
                education = 0
            else:
                education = 1


        def getEmployment():
            employment = 0
            if customer.Employment == Customer.objects.get(Employment = 
                "Student"):
                employment = 0
            elif customer.Employment == Customer.objects.get(Employment = 
                "Contract"):
                employment = 1
            else:
                employment = 2


        def getStability():
            stability = 0
            if customer.Employer_Stability == 
              Customer.objects.get(Employer_Stability = "Unstable"):
                stability = 0
            else:
                stability = 1


        def getResidential():
            residential = 0
            if customer.Residential_Status == 
                Customer.objects.get(Residential_Status = "Rented"):
                residential = 0
            else:
                residential = 1


        def getSalary():
            salary = 0
            if customer.Salary == Customer.objects.get(Salary <= 1000):
                salary = 0
            elif customer.Salary == Customer.objects.get(Salary <= 10001 and 
                Salary > 1000):
                salary = 1
            else:
                salary = 2


        def getLoyalty():
            loyalty = 0
            loy = Customer.objects.get(Customer_Loyalty <= 2)

            if customer.Customer_Loyalty == loy.Customer_Loyalty:
                loyalty = 0
            else:
                loyalty = 1


        def getBalance():
            balance = 0
            if customer.Balance == Customer.objects.get(Balance <= 2500):
                balance = 0
            elif customer.Balance == Customer.objects.get(Balance <= 10001 
                and Balance > 2500):
                balance = 1
            else:
                balance = 2



        def feat_list():
            total = getAge + getEducation + getEmployment + getStability + 
                getResidential + getSalary + getLoyalty + getBalance
            return total



        if feat_list() <= 11:
            customer.Service_Level = Service.objects.get(service_name = 
                'Silver Package')
            silver_customers.append(customer.Name)

        elif 11 < feat_list() <= 15:
            customer.Service_Level = Service.objects.get(service_name = 
                'Gold Package')
            gold_customers.append(customer.Name)
        elif feat_list() > 15:
            customer.Service_Level = Service.objects.get(service_name = 
                "Platinum Package")
            platinum_customers.append(customer.Name)
        else:
            customer.Service_Level = Service.objects.get(service_name = "No 
                Service Package")
            non_customers.append(customer.name)

        customer.save()

        if platinum_customers:
            message = 'The following customers are now Platinum Customers: 
                {}'.format(', '.join(platinum_customers))
        if silver_customers:
            message = 'The following customers are now Silver Customers: 
                {}'.format(', '.join(silver_customers))
        if gold_customers:
            message = 'The following customers are now Gold Customers: 
                {}'.format(', '.join(gold_customers))
        if not platinum_customers and not silver_customers and not          
               gold_customers:
             message = 'No customer changes made!'
        ModelAdmin.message_user(request, message, level=SUCCESS)
    allocate_service.short_description = 'Allocate Service'

我想运行代码的这一部分以确定Service Level的值:

    if feat_list() <= 11:
        customer.Service_Level = Service.objects.get(service_name = 'Silver Package')
        silver_customers.append(customer.Name)

    elif 11 < feat_list() <= 15:
        customer.Service_Level = Service.objects.get(service_name = 'Gold Package')
        gold_customers.append(customer.Name)
    elif feat_list() > 15:
        customer.Service_Level = Service.objects.get(service_name = "Platinum Package")
        platinum_customers.append(customer.Name)
    else:
        customer.Service_Level = Service.objects.get(service_name = "No Service Package")
        non_customers.append(customer.name)

    customer.save()

问题在于它为每个查询集提供Service Level Silver Packages即使我已经自定义编辑了一些以获得Platinum or Gold Packages。我不确定这个块究竟出了什么问题。它正在运行但提供了一个不需要的输出

1 个答案:

答案 0 :(得分:0)

我认为代码应该在每个函数上使用你的装饰器,否则你只是将get age评估为可操作的。

  1. 您需要将装饰器添加到您正在评估的每个功能
  2. 您需要返回每个子操作的结果(因此您可以将其与feat_list()相加)
  3. 这就是为什么你得到一个低于11的分数,所以你最终得到了silver_customers。 打印总变量非常重要,因此很容易跟踪结果:

      # This class allows function addition, multiplication, division 
                etc.
    class operable:
       def __init__(self, f):
            self.f = f
       def __call__(self, x):
            return self.f(x)
    
    def op_to_function_op(op):
       def function_op(self, operand):
            def f(x):
                return op(self(x), operand(x))
            return operable(f)
       return function_op
    
     for name, op in [(name, getattr(operator, name)) for name in 
        dir(operator) if "__" in name]:
        try:
            op(1,2)
        except TypeError:
            pass
        else:
            setattr(operable, name, op_to_function_op(op))
    
     def allocate_service(ModelAdmin, request, queryset):
        platinum_customers = []
        silver_customers = []
        gold_customers = []
        non_customers = []
        message = ''
    
    
        for customer in queryset:
    
            @operable
            def getAge():
                age = 0
    
                if customer.Age == Customer.objects.get(Age = "60 +"):
                    age = 0
    
                elif customer.Age == Customer.objects.get(Age = "36 - 59"):
                    age = 1
                else:
                    age = 2
                return age
    
            @operable
            def getEducation():
                education = 0
                if customer.Education == Customer.objects.get(Education = 
                    "Highschool and below"):
                    education = 0
                else:
                    education = 1
                return education
            @operable
            def getEmployment():
                employment = 0
                if customer.Employment == Customer.objects.get(Employment = 
                    "Student"):
                    employment = 0
                elif customer.Employment == Customer.objects.get(Employment = 
                    "Contract"):
                    employment = 1
                else:
                    employment = 2
                return employment
    
            @operable
            def getStability():
                stability = 0
                if customer.Employer_Stability == 
                  Customer.objects.get(Employer_Stability = "Unstable"):
                    stability = 0
                else:
                    stability = 1
                return stability 
    
            @operable
            def getResidential():
                residential = 0
                if customer.Residential_Status == 
                    Customer.objects.get(Residential_Status = "Rented"):
                    residential = 0
                else:
                    residential = 1
                return residential 
    
            @operable
            def getSalary():
                salary = 0
                if customer.Salary == Customer.objects.get(Salary <= 1000):
                    salary = 0
                elif customer.Salary == Customer.objects.get(Salary <= 10001 and 
                    Salary > 1000):
                    salary = 1
                else:
                    salary = 2
                return salary
            @operable
            def getLoyalty():
                loyalty = 0
                loy = Customer.objects.get(Customer_Loyalty <= 2)
    
                if customer.Customer_Loyalty == loy.Customer_Loyalty:
                    loyalty = 0
                else:
                    loyalty = 1
                return loyalty 
            @operable
            def getBalance():
                balance = 0
                if customer.Balance == Customer.objects.get(Balance <= 2500):
                    balance = 0
                elif customer.Balance == Customer.objects.get(Balance <= 10001 
                    and Balance > 2500):
                    balance = 1
                else:
                    balance = 2
                return balance
    
    
            def feat_list():
                total = getAge + getEducation + getEmployment + getStability + 
                    getResidential + getSalary + getLoyalty + getBalance
                print('total:' + total)
                return total
    
    
    
            if feat_list() <= 11:
                customer.Service_Level = Service.objects.get(service_name = 
                    'Silver Package')
                silver_customers.append(customer.Name)
    
            elif 11 < feat_list() <= 15:
                customer.Service_Level = Service.objects.get(service_name = 
                    'Gold Package')
                gold_customers.append(customer.Name)
            elif feat_list() > 15:
                customer.Service_Level = Service.objects.get(service_name = 
                    "Platinum Package")
                platinum_customers.append(customer.Name)
            else:
                customer.Service_Level = Service.objects.get(service_name = "No 
                    Service Package")
                non_customers.append(customer.name)
    
            customer.save()
    
            if platinum_customers:
                message = 'The following customers are now Platinum Customers: 
                    {}'.format(', '.join(platinum_customers))
            if silver_customers:
                message = 'The following customers are now Silver Customers: 
                    {}'.format(', '.join(silver_customers))
            if gold_customers:
                message = 'The following customers are now Gold Customers: 
                    {}'.format(', '.join(gold_customers))
            if not platinum_customers and not silver_customers and not          
                   gold_customers:
                 message = 'No customer changes made!'
            ModelAdmin.message_user(request, message, level=SUCCESS)
        allocate_service.short_description = 'Allocate Service'