我想调用嵌套在外部函数中的函数,但会引发错误。
问题:如果车主是“要人”,则不需要收取通行费,但车辆数目应予以更新。对于任何其他类型的车主,计算收费金额并更新车辆数量。
class Tollbooth:
count = 0
def init(self):
self.__no_of_vehicle=0
self.__total_amount=0
def get_no_of_vehicle(self):
return self.__no_of_vehicle
def get_total_amount(self):
return self.__total_amount
def calculate_amount(vehicle_type):
if(vehicle_type == "Car"):
self.__total_amount = 70
elif(vehicle_type=="Bus"):
self.__total_amount =100
elif(vehicle_type == "Truck"):
self.__total_amount=150
else:
self.__total_amount=70
return self.__total_amount
def count_vehicle(self):
Tollbooth.count+=1
return Tollbooth.count
def collect_toll(self,owner_type,vehicle_type):
if(owner_type=="VIP"):
count_vehicle(self)
else:
count_vehicle(self)
calculate_amount(vehicle_type)
T1=Tollbooth()
T1.collect_toll("VIP","Car")发布于 2021-04-27 21:34:51
有很多不对劲的地方。
init方法。self。错误显示变量不存在,因为要调用它,需要使用self.count_vehicles。self还需要作为所有方法的第一个参数传递,我看到您后来忘记了这一点。self。它会自动通过就像赫斯基说的那样,我强烈建议你读Python类文档。
因此,在修复代码之后,这是最后的工作代码。
class Tollbooth:
count = 0
def __init__(self):
self.__no_of_vehicle=0
self.__total_amount=0
def get_no_of_vehicle(self):
return self.__no_of_vehicle
def get_total_amount(self):
return self.__total_amount
def calculate_amount(self,vehicle_type):
if(vehicle_type == "Car"):
self.__total_amount = 70
elif(vehicle_type=="Bus"):
self.__total_amount =100
elif(vehicle_type == "Truck"):
self.__total_amount=150
else:
self.__total_amount=70
return self.__total_amount
def count_vehicle(self):
Tollbooth.count+=1
return Tollbooth.count
def collect_toll(self,owner_type,vehicle_type):
if(owner_type=="VIP"):
self.count_vehicle()
else:
self.count_vehicle()
self.calculate_amount(vehicle_type)
T1=Tollbooth()
T1.collect_toll("VIP","Car")发布于 2021-04-27 21:24:28
我想你对self是如何使用的感到困惑。据我所知,self用于指定特定类的作用域,因此不应该使用self作为函数的参数。
假设您使用的是Python3,请看一看Python类文档。
https://stackoverflow.com/questions/67290796
复制相似问题