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

Python栈类继承问题求助:子类继承父类属性触发TypeError

Fixing Your Stack3 Inheritance Error

Hey there! Let's break down what's causing the TypeError in your code and fix it step by step.

What's Going Wrong?

Your error stems from three key issues in the Stack3 subclass implementation:

  1. Missing required argument when creating Stack3 instance
    You defined Stack3.__init__() with a mandatory __list parameter, but tried to create an instance with s = Stack3() (no arguments passed). This directly triggers the "missing positional argument" error.

  2. Incorrect parent constructor call
    The parent Stack class's __init__() method takes no arguments (other than self), but you're calling super().__init__(self.__list) which passes an extra parameter—this would cause another error even if you did supply __list.

  3. Unnecessary private variable redefinition
    In Python, double-underscore variables undergo name mangling: the parent's __list becomes _Stack__list, while your subclass's __list becomes _Stack3__list—these are two separate variables. You don't need to redefine this list, since the parent class already initializes it.

Fixed Code

Here's the corrected version of your Stack3 class and usage code:

class Stack:
    def __init__(self):
        self.__list= []
    def isEmpty(self):
        return self.__list == []
    def size(self):
        return len(self.__list)
    def clear(self):
        self.__list.clear()
    def push(self, item):
        self.__list.append(item)
    def pop(self):
        if self.isEmpty():
            return None
        else:
            return self.__list.pop()
    def get(self):
        if self.isEmpty():
            return None
        else:
            return self.__list[-1]
    def __str__(self):
        output = '<'
        for i in range( len(self.__list) ):
            item = self.__list[i]
            if i < len(self.__list)-1 :
                output += f'{str(item)}, '
            else:
                output += f'{str(item)}'
        output += '>'
        return output

class Stack3(Stack):
    def __init__(self):
        # Call parent constructor to initialize the underlying list
        super().__init__()
    
    def printMe(self):
        # Actually print the string generated by the parent's __str__ method
        print(super().__str__())

s = Stack3()
print(s.pop())
for i in range(1,6):
    s.push(i)
print('Content of stack =',s)
print('Item at top=',s.get())
print('Size=', s.size())
while not s.isEmpty():
    print(s.pop())
print(s)

Key Changes Explained

  • Simplified Stack3.__init__(): Removed the __list parameter and called super().__init__() without arguments, letting the parent class handle initializing the empty list.
  • Fixed printMe(): The original code called super().__str__() but didn't do anything with the resulting string—now it prints it directly.
  • Proper inheritance: Stack3 now correctly inherits all the functionality from Stack without overriding or redefining unnecessary variables.

Expected Output

When you run the fixed code, you'll get this output:

None
Content of stack = <1, 2, 3, 4, 5>
Item at top= 5
Size= 5
5
4
3
2
1
<>

内容的提问来源于stack exchange,提问作者rageyboi123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:17:30