简体   繁体   中英

Executing a method from a parent class in a child class

I am trying to create a new attribute for the child class SubClass by using a method in the parent class MyClass . This method – method_of_class – should take an array from the child class SubClass as an argument and return a value result .

The following is just some dummy code to clearly illustrate what I am trying to achieve:

import numpy as np


class MyClass:
    def __init__(self,var1,var2):
        self.var1 = var1
        self.var2 = var2
        
        self.class_array = np.array([[self.var1, self.var2],
                                     [-self.var2, self.var1]])
        
    def method_of_class(self,some_array):

        intermediate_array = np.matmul(some_array, self.class_array)
        result = np.matmul(self.class_array.transpose(), intermediate_array)

        return result
        
        
class SubClass(MyClass):
    def __init__(self,var1,var2,var3,var4):
        super().__init__(var1,var2)
        super().method_of_class(some_array)
        self.var3 = var3
        self.var4 = var4
        
        self.subclass_array = np.array([[self.var3, self.var4],
                                        [self.var4, self.var3]])
        
        self.new_array = method_of_class(self.subclass_array)

d = SubClass(1,1,1,1)
print(d.new_array)

The code does not work, and I get the following error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-68-8b58ebadf6be> in <module>
----> 1 d = SubClass(1,1,1,1)
      2 
      3 print(d.new_array)

<ipython-input-67-66bf10d774f2> in __init__(self, var1, var2, var3, var4)
     19     def __init__(self,var1,var2,var3,var4):
     20         super().__init__(var1,var2)
---> 21         super().method_of_class(some_array)
     22         self.var3 = var3
     23         self.var4 = var4

NameError: name 'some_array' is not defined

When you inherit from a class, its methods become available to instances of the child class, so there is no need to write super().method_of_class(some_array) . Especially because you did not define the variable some_array when doing so.

Instead, simply state that you want to use method_of_class from this instance when creating self.new_array :

class SubClass(MyClass):
    def __init__(self,var1,var2,var3,var4):
        super().__init__(var1,var2)
        self.var3 = var3
        self.var4 = var4
        
        self.subclass_array = np.array([[self.var3, self.var4],
                                        [self.var4, self.var3]])
        
        self.new_array = self.method_of_class(self.subclass_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM