Python栈类继承问题求助:子类继承父类属性触发TypeError
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:
Missing required argument when creating
Stack3instance
You definedStack3.__init__()with a mandatory__listparameter, but tried to create an instance withs = Stack3()(no arguments passed). This directly triggers the "missing positional argument" error.Incorrect parent constructor call
The parentStackclass's__init__()method takes no arguments (other thanself), but you're callingsuper().__init__(self.__list)which passes an extra parameter—this would cause another error even if you did supply__list.Unnecessary private variable redefinition
In Python, double-underscore variables undergo name mangling: the parent's__listbecomes_Stack__list, while your subclass's__listbecomes_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__listparameter and calledsuper().__init__()without arguments, letting the parent class handle initializing the empty list. - Fixed
printMe(): The original code calledsuper().__str__()but didn't do anything with the resulting string—now it prints it directly. - Proper inheritance:
Stack3now correctly inherits all the functionality fromStackwithout 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

