python - 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())
有人可以告诉我我错过了什么吗?
解决方案
你没有打电话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
在不需要任何混合类的情况下使用的常规函数。
推荐阅读
- postgresql - TypeOrm 比较逗号分隔的字符串
- spring-boot - waitingList 实体的优先级队列
- python - 对象作为 Python 多处理池的参数默认为相同的对象内存(错误)
- bash - env 未从命令结果导出
- r - kSamples r 包中 Anderson-Darling 的事后多重比较测试
- javascript - 将数据从 javascript forEach 循环中的 php 数组发送到 ajax 调用的 url
- r - 使用过滤器在 R 中制作条形图
- java - MongoDB 在原子操作中查找和删除多个文档
- revit-api - Autodesk Forge 能否利用 CopyElements 方法(Document、ICollection(ElementId)、Document、Transform、CopyPasteOptions)方法?
- javascript - 提交 html 表单需要 2 次点击(无 Ajax)