2

I defined a class and within that class, created some methods. In one of the methods I wish to call another method. What is the reason that I cannot call the method by placing "self" into the argument? For example, method2(self).

3 Answers 3

2

There are languages that let you write method2() as a shorthand for (what in Python would be) self.method2(), but you can't in Python. Python doesn't treat the self argument as special inside the function (except when calling super()).

In Python, method2(self) first of all looks up method2 in the current scope. It seems like it should be in scope, but it actually isn't because of Python's weird scoping rules. Nothing in any class scope is ever visible in nested scopes:

x = 1

class A:
    x = 2

    print(x)  # prints 2

    def method(self):
        print(x)  # prints 1

    class B:
        print(x)  # prints 1

Even if method2 was in scope, calling it directly would call the method from the class currently being defined, not the overridden method appropriate to the dynamic type of self. To call that, you must write self.method2().

Sign up to request clarification or add additional context in comments.

1 Comment

could you explain what you mean by "dynamic type of self"?
1

The self parameter is automatically passed in as the object you are calling the method from. So if I said self.method2(), it automatically figures out that it is calling self.method2(self)

2 Comments

self.method2(self) is not the same as self.method2().
For normal methods, self.method() is equivalent to type(self).method(self), I'm guessing that's what you were trying to write.
0

You can call a method with self as an argument, but in this case the method should be called as the method of the class, not the instance.

class A:
    def method1(self):
        print(1)

    def method2(self):
        A.method1(self)

a = A()
a.method2()
# 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.