2016-03-06 89 views
0

我想从父类继承变量到子类。但是,我正面临属性错误。请在下面找到我的代码: -继承时出现属性错误

class Stack1(object): 
    def __init__(self): 
     self.stack1 = [] 

    def push(self, item): 
     self.stack1.append(item) 
    def pop(self): 
     self.popped_value = self.stack1.pop()  
     print("popped_value parent", self.popped_value) 
    def peek(self): 
     try: 
      return self.stack1[len(stack1)-1] 
     except: 
      print("Cannot peek into stack 1") 
    def is_empty(self): 
     if len(self.stack1) == 0: 
      return True 
     else: 
      return False 
    def display(self): 
     print(self.stack1) 

class Stack2(Stack1): 
    def __init__(self): 
     self.stack2 = []   

    def push(self): 
     #popped_value = Stack1.pop(self) 
     #popped_value = super(Stack2, self).pop() 
     super(Stack2, self).pop() 
     print("popped_value child", self.popped_value) 
     self.stack2.append(popped_value) 
    def pop(self): 
     return self.stack2.pop() 
    def peek(self): 
     try: 
      return self.stack2[len(stack2)-1] 
     except: 
      print("Cannot peek into stack 2") 
    def is_empty(self): 
     if len(self.stack2) == 0: 
      return True 
     else: 
      return False 
    def display(self): 
     print(self.stack2) 

first_stack = Stack1() 
second_stack = Stack2() 

first_stack.push(1) 
first_stack.push(2) 
first_stack.display() 
print("Pushed above items into stack1") 
first_stack.pop() 
second_stack.push() 
second_stack.display() 
print("Pushed above items into stack2") 
first_stack.pop() 
second_stack.push() 
second_stack.display() 
print("Pushed above items into stack2") 

下面是错误: -

E:\>python dsq.py 
[1, 2] 
Pushed above items into stack1 
popped_value parent 2 
Traceback (most recent call last): 
    File "dsq.py", line 56, in <module> 
    second_stack.push() 
    File "dsq.py", line 30, in push 
    super(Stack2, self).pop1() 
    File "dsq.py", line 8, in pop1 
    self.popped_value = self.stack1.pop() 
AttributeError: 'Stack2' object has no attribute 'stack1' 

在这里,我想实现使用两个堆栈队列。所以,我试图将弹出的物品从第一个堆栈推到第二个堆栈。所以,为了实现这一点,我需要从第一个堆栈访问popped_item到我的子类Stack2。

你能帮我解决吗?

+0

为什么你在这里使用继承?两个堆栈不应该是同一个类的实例吗? – jonrsharpe

回答

2

Python在父类初始化程序(Stack1.__init__)未被派生类自动调用的方式中颇为独特;你需要确保它自己:

class Stack2(Stack1): 
    def __init__(self): 
     super().__init__() # call the __init__ method of the super class 
     self.stack2 = []   

顺便说一句,你不继承只有1变量,你继承所有父类的,你没有在孩子重写的行为。

+0

谢谢。这是一个学习点。 – Sourav