【问题标题】:If statement only producing one output for all conditionsIf 语句只为所有条件产生一个输出
【发布时间】:2017-05-11 03:07:41
【问题描述】:

我在 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()

问题在于,即使我自定义编辑了一些以获取Platinum or Gold Packages,它也会为每个查询集提供Silver PackagesService Level。我不确定这个块到底有什么问题。它正在运行,但提供了不需要的输出

【问题讨论】:

  • 你的代码包含很多ifs;我们不知道您遇到了哪些具体问题。尝试编辑您的问题以包含运行代码的示例,以及说明问题的输出。
  • 好的,我来做吧
  • 另外,不清楚是否在父函数中定义了内部函数等。缩进需要再看一下
  • 不应该total = getAge + getEducation + getEmployment + getStability + getResidential + getSalary + getLoyalty + getBalance在每个get之后都有()吗?
  • 我已经更新了正确的缩进。 @KenY-N 我尝试添加 () 并收到错误 TypeError: __call__() takes exactly 2 arguments (1 given)

标签: python django decorator


【解决方案1】:

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

  1. 您需要将装饰器添加到您正在评估的每个函数中
  2. 您需要返回每个子操作的结果(这样您就可以将其与 feat_list() 相加)

这就是为什么您收到的分数低于 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'

【讨论】:

  • 直到产生相同的输出
猜你喜欢
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 2017-09-25
相关资源
最近更新 更多