下面的代码应该将customer对象的描述方法返回的值打印到没有的terminal...but。问题似乎是NameError:没有定义名称‘价格’。
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())谁能告诉我错过了什么吗?
发布于 2021-06-06 16:17:15
你没给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可以使用的常规函数,而不需要任何混合类。
发布于 2021-06-06 16:23:38
切普纳是对的。您必须在您的calculate_ticket_price init函数中调用。正确的语法是使用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}"您可以通过单击这里来了解有关超级关键字的更多信息。
https://stackoverflow.com/questions/67861189
复制相似问题