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).
CodePudding user response:
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()
.
CodePudding user response:
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)
CodePudding user response:
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