【发布时间】:2021-08-23 22:07:52
【问题描述】:
我下面的代码应该将客户对象的 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())
谁能告诉我我错过了什么?
【问题讨论】:
-
price是calculate_ticket_price中的局部变量,而不是name或age之类的属性。您必须致电calculate_ticket_price获取价值。 -
呃,我真傻。谢谢!
标签: python mixins python-class