首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NameError:未定义名称“count_vehicle”

NameError:未定义名称“count_vehicle”
EN

Stack Overflow用户
提问于 2021-04-27 21:18:21
回答 2查看 228关注 0票数 0

我想调用嵌套在外部函数中的函数,但会引发错误。

问题:如果车主是“要人”,则不需要收取通行费,但车辆数目应予以更新。对于任何其他类型的车主,计算收费金额并更新车辆数量。

代码语言:javascript
复制
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")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-27 21:34:51

有很多不对劲的地方。

  • 应该用双下划线调用init方法。
  • 每当您想访问类的成员变量或方法时,都需要使用self。错误显示变量不存在,因为要调用它,需要使用self.count_vehicles
  • self还需要作为所有方法的第一个参数传递,我看到您后来忘记了这一点。
  • 调用方法时,不需要传递self。它会自动通过

就像赫斯基说的那样,我强烈建议你读Python类文档

因此,在修复代码之后,这是最后的工作代码。

代码语言:javascript
复制
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")
票数 2
EN

Stack Overflow用户

发布于 2021-04-27 21:24:28

我想你对self是如何使用的感到困惑。据我所知,self用于指定特定类的作用域,因此不应该使用self作为函数的参数。

假设您使用的是Python3,请看一看Python类文档

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67290796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档