-2

In python's OOPs concept, a instance of class to be made to call other methods. I had a good explanation about self by arjun-sreedharan, how self works.

His explanation,

Let's say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.


But in my case, consider the same example given above. If methodA is called without instance of class. How the internal convention of python is?

I mean, if methodA is called like this --> ClassA().methodA(arg1, arg2). How would python assign the self. Because in my case i have not declared any instance of class like this ObjectA = ClassA().

M.sainath
  • 15
  • 1
  • 6

1 Answers1

0

It will create a new ClassA instance internally:

class ClassA:
    def methodA(self):
        return "hey"
    
A = ClassA()
print(A.methodA())
# output : "hey"
print(ClassA.methodA())
# error
print(ClassA().methodA())
# output : "hey"

Error you would get with ClassA.methodA()

TypeError: methodA() missing 1 required positional argument: 'self'

Internal representation of ClassA().methodA(arg1, arg2):

ClassA.methodA(temporary_variable, arg1, arg2)

Since temporary_variable is not reachable by us, garbage collector will remove that object after a while.
Unreachable memory is a block memory occupied by the program that has no longer reachable pointer that refers to it.

Muhteva
  • 2,729
  • 2
  • 9
  • 21
  • `ClassA().methodA(arg1, arg2)` is given in the question not what you tried – python_user Aug 27 '21 at 10:55
  • ```print(ClassA().methodA(2, 3))```. I'm asking for this, can you get my point. – M.sainath Aug 27 '21 at 10:59
  • ok, that's not problem. so if it is ```print(ClassA().methodA(2, 3))```. What is the internal convention would be? because in this case object was not created, how self is assigned. – M.sainath Aug 27 '21 at 11:03
  • Actually object is created. When you do this: ```A = ClassA()``` You actually do two things: Create a ```ClassA``` instance and then assign it to a variable called ```A```. What we do here is that we create a ```ClassA``` instance but we do not assign it to any variable. (But of course it is stored in the memory). So self is assigned like this: ```ClassA.methodA(temporary_variable, arg1, arg2)``` – Muhteva Aug 27 '21 at 11:06
  • By doing ```ClassA().methodA(arg1, arg2)```, we actually create an unreachable ClassA object, which will be deleted by the garbage collector after a while. Refer to [here](https://stackoverflow.com/a/9449506/16530078) – Muhteva Aug 27 '21 at 11:09
  • Thankyou for you answer. – M.sainath Aug 27 '21 at 11:15