-1

I'm working with arrays and I'm trying to create a function that returns or prints all the names of the functions of a class. I want to print it, but I get the same error

missing 1 required positional argument: 'self'

The code is:

import numpy as np
class Operation:
    def __init__(self, array1, array2):
        self.array1 = array1
        self.array2 = array2
        print("Input arrays:", array1, "and", array2)

    def get_functions_names(self):
        listofmethods = self.dir(Operation)[-2:]
        return listofmethods

    def element_wise_addition(self):
        addition_result = self.array1 + self.array2
        return addition_result



trial= Operation()
print(trial.get_functions_names())

Is it because I'm defining the two arrays in the constructor? Should I create a separate class?

talonmies
  • 70,661
  • 34
  • 192
  • 269

2 Answers2

0

Add default value to array1 and array2:

class Operation:
    def __init__(self, array1 = None, array2 = None):
        if array1 is None:
            array1 = []
        if array2 is None:
            array2 = []

        self.array1 = array1
        self.array2 = array2
Vikas Zingade
  • 134
  • 1
  • 2
  • 5
0

As Vikas answer shows you to see if an array is "None" you can use an empty array by default. No need to make it more complicated than needed. Just overwrite when needed.

dir is a standalone method, wrapping it on self won't make sense. From below code you get the result:

Input arrays: [] and []

and

['element_wise_addition', 'get_functions_names']


import numpy as np
class Operation():
    def __init__(self, array1=[], array2=[]):
        self.array1 = array1
        self.array2 = array2
        print("Input arrays:", array1, "and", array2)

        # functional string option.
#        print(f"Input arrays 1: {array1}, and 2: {array2}") 

    def get_functions_names(self):
        listofmethods = dir(Operation)[-2:]
        return listofmethods

    def element_wise_addition(self):
        addition_result = self.array1 + self.array2
        return addition_result



trial= Operation()
print(trial.get_functions_names())

if your using Vikas answer and want to circumvent

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

then you should use the following to replace the immutable type:

    def element_wise_addition(self):
        
        if self.array1 == None:   # or use for example "isinstance()" method, etc
            self.array1 = []
        
        if self.array2 == None:
            self.array2 = []
        
        addition_result = self.array1 + self.array2
        return addition_result
ZF007
  • 3,708
  • 8
  • 29
  • 48
  • In Python, using mutable types for function default arguments results in unwanted behaviour. See for more detailed explanation - https://stackoverflow.com/a/63329315/6298926 – Vikas Zingade Dec 10 '21 at 10:21