NameError:名称“”未定义

问题描述

我下面的代码应该将客户对象的 describe 方法的返回值打印到终端......但它没有。问题似乎是 NameError: name 'price' 未定义。

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

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

解决方法

您没有拨打 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 可以或者接受一个 age 参数,在这种情况下,它不需要假设 self.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 使用而无需任何混合类的常规函数​​。

,

切普纳是对的。您必须在 init 函数中调用 calculate_ticket_price。正确的语法是使用 super 关键字。

示例:

class Customer(TicketMixin):
    """ Create instance of Customer """
    def __init__(self,name,age,):
        self.name = name
        self.age = age
        self.price = super().calculate_ticket_price(self.age)
    
    def describe(self):
        return f"{self.name} age {self.age} ticket price is {self.price}"

您可以通过点击 here 了解有关 super 关键字的更多信息。