[英]Error in Python: missing 1 required positional argument: 'self'
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.我正在使用 arrays 并且我正在尝试创建一个 function 来返回或打印 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?是因为我在构造函数中定义了两个 arrays 吗? Should I create a separate class?
我应该创建一个单独的 class 吗?
Add default value to array1
and array2
:为
array1
和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
As Vikas answer shows you to see if an array is "None" you can use an empty array by default.正如 Vikas 的回答向您展示的那样,您可以查看数组是否为“无”,默认情况下您可以使用空数组。 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. dir 是一个独立的方法,将它包装在 self 上没有意义。 From below code you get the result:
从下面的代码你得到结果:
Input arrays: [] and []
输入 arrays:[] 和 []
and和
['element_wise_addition', 'get_functions_names']
['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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.