Mukund Gandlur Mukund Gandlur - 6 months ago 20
Python Question

missing 1 required positional argument:'self' when assigning a method to a variable

I am trying to assign a method's return to a variable and stuck with this error.

class MyClass():

def my_def(self):
return "Hello"

my_variable = my_def()


Here is the Java equivalent of what I want to do.

public class NewException {
public int method1(){

return 1;
}
public int variable = method1();
}


I am sure this is something simple, but I couldn't even find the right words to google this. Any help is appreciated.

Answer

Lets start with the difference between methods and functions, basically a method belongs to some object while a function does not. So for example

def myFunction():
    return "F"

class MyClass:
    value = 0
    def myMethod(self, value):
        old = self.value
        self.value = value
        return old

myClassInstance = MyClass()
print myClassInstance.myMethod(3)
# 0
print myClassInstance.myMethod(33)
# 3
print myFunction()
# F

Notice that the method is bound to the instance and it doesn't make sense to call the method before the instance is created. With that in mind, your error should make more sense. The method cannot be called without an instance (self). This is not the only kind of method, for example there are "static methods". Static methods are defined on the class, but they are called without an instance. For example:

class MyClass:
    @staticmethod
    def myStaticMethod():
        return "static method"
    # Consider using an instance attribute instead of a class attribute
    def __init__(self):
        self.instance_attribute = MyClass.myStaticMethod()
# Or if you need a class attribute it needs to go outside the class block
MyClass.class_attribute = MyClass.myStaticMethod()