夏瑾 发表于 2025-4-17 15:34:33

构造函数出现BUG

class C:
    def _init_(self,x,y):
      self.x = x
      self.y = y
      def add(self):
            return self.x+self.y
      def mul(self):
            return self.x*self.y

      
KeyboardInterrupt
c=C(2,3)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
    c=C(2,3)
TypeError: C() takes no arguments
C.add()
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
    C.add()
AttributeError: type object 'C' has no attribute 'add'
c.__dict__
mappingproxy({'__module__': '__main__', '__firstlineno__': 1, '_init_': <function c._init_ at 0x000002012D5AA0C0>, '__static_attributes__': ('x', 'y'), '__dict__': <attribute '__dict__' of 'c' objects>, '__weakref__': <attribute '__weakref__' of 'c' objects>, '__doc__': None})
c.add()
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
    c.add()
AttributeError: type object 'c' has no attribute 'add'

FishC 发表于 2025-4-17 15:35:15

问题分析及解决方法

你的代码存在三个主要问题:

1. 构造函数命名错误:Python的构造函数必须是双下划线 __init__,而你写成了单下划线 _init_

2. 方法缩进错误:add和mul方法被错误地缩进到构造函数内部,变成了嵌套函数

3. 实例方法调用错误:类方法应该通过实例调用(c.add()),而不是类直接调用(C.add())

修正后的代码


class C:
    def __init__(self, x, y):# 修正双下划线
      self.x = x
      self.y = y

    # 方法应与__init__保持同级缩进
    def add(self):
      return self.x + self.y
   
    def mul(self):
      return self.x * self.y


测试验证

c = C(2, 3)
print(c.add())# 输出5
print(c.mul())# 输出6


修正要点:

[*]检查构造函数命名规范
[*]确保方法定义在类作用域层级
[*]通过实例调用方法而非直接使用类调用


以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

夏瑾 发表于 2025-4-17 16:05:22

FishC AI 小助理解答很专业
页: [1]
查看完整版本: 构造函数出现BUG