You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python求助:CountingClicker() takes no arguments报错及计数查看需求

问题解决:CountingClicker类实例化错误与计数查看实现

错误根源

你定义的CountingClicker类里,构造函数写成了_init_(单下划线),但Python要求类的构造函数必须是双下划线开头和结尾的__init__。因为代码里没有正确定义构造函数,Python会使用默认的无参构造函数,所以传入count=100参数时就会触发TypeError: CountingClicker() takes no arguments错误。

修正并完善后的代码

将构造函数的下划线改为双下划线,同时添加查看计数的功能,代码如下:

class CountingClicker:
    # 正确的构造函数:双下划线__init__
    def __init__(self, count=0):
        self.count = count
    
    # 方法1:主动获取当前计数
    def get_count(self):
        return self.count
    
    # 方法2:打印实例时直接显示计数信息
    def __str__(self):
        return f"当前计数:{self.count}"

测试验证

执行实例化和查看计数的代码:

# 无参实例化
clicker1 = CountingClicker()
print(clicker1.get_count())  # 输出:0
print(clicker1)  # 输出:当前计数:0

# 带参数实例化
clicker2 = CountingClicker(count=100)
print(clicker2.get_count())  # 输出:100
print(clicker2)  # 输出:当前计数:100

内容的提问来源于stack exchange,提问作者Letícia Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:37:20