Home > Software design >  Error in Python: missing 1 required positional argument: 'self'
Error in Python: missing 1 required positional argument: 'self'

Time:12-07

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?

CodePudding user response:

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

CodePudding user response:

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)

    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())
  • Related