首页 > 解决方案 > NameError:名称“”未定义

问题描述

我下面的代码应该将客户对象的 describe 方法的返回值打印到终端……但事实并非如此。问题似乎是 NameError: name 'price' is not defined。

class TicketMixin:
    
    """ Mixin to calculate ticket price based on age """
    def calculate_ticket_price(self, age):
        
        ticket_price = 0
        price = ticket_price
        
        if self.age < 12:
            price = ticket_price + 0
        elif self.age < 18:
            price = ticket_price + 15
        elif self.age < 60:
            price = ticket_price + 20
        elif self.age >= 60:
            price = ticket_price + 10
        return price

class Customer(TicketMixin):
    """ Create instance of Customer """
    def __init__(self, name, age,):
        self.name = name
        self.age = age
    
    def describe(self):
        return f"{self.name} age {self.age} ticket price is {price}"
        
customer = Customer("Ryan Phillips", 22)
print(customer.describe())

有人可以告诉我我错过了什么吗?

标签: pythonmixinspython-class

解决方案


你没有打电话calculate_ticket_price

def describe(self):
    return f"{self.name} age {self.age} ticket price is {self.calculate_ticket_price(self.age)}"

请注意,可以calculate_ticket_price接受一个参数,在这种情况下它不需要假设存在:ageself.age

class TicketMixin:
    
    """ Mixin to calculate ticket price based on age """
    def calculate_ticket_price(self, age):
        
        ticket_price = 0
        price = ticket_price
        
        if age < 12:
            price = ticket_price + 0
        elif age < 18:
            price = ticket_price + 15
        elif age < 60:
            price = ticket_price + 20
        elif age >= 60:
            price = ticket_price + 10
        return price

或者您可以做出该假设并完全摆脱该age参数:

class TicketMixin:
    
    """ Mixin to calculate ticket price based on age """
    def calculate_ticket_price(self):
        
        ticket_price = 0
        price = ticket_price
        
        if self.age < 12:
            price = ticket_price + 0
        elif self.age < 18:
            price = ticket_price + 15
        elif self.age < 60:
            price = ticket_price + 20
        elif self.age >= 60:
            price = ticket_price + 10
        return price

然后主体describe将简单地省略任何显式参数:

def describe(self):
    return f"{self.name} age {self.age} ticket price is {self.calculate_ticket_price()}"

在前者中,请注意您在定义中根本不self 使用;这表明它应该是一个静态方法,或者只是一个可以Customer在不需要任何混合类的情况下使用的常规函数​​。


推荐阅读