tez
tez

Reputation: 5300

actual objects and its references in python

I'm a bit confused about actual object and its reference in python.Googled a lot but didn't get what I need.

Does object creation also returns a reference to that object? Why i'm asking this is because I'm able to use actual object with . delimiter to call its methods.We usually use reference of the object to call methods.An example might give a clear idea of what I'm asking.

l = [2,4,1,3] # 'l' is a reference to actual object.Right?

does the RHS part create the object and return a reference to that object which'll be assigned to LHS ?

Because I'm able to use both list.sort() and [2,4,1,3].sort() to sort the list. Is [2,4,1,3] an actual object or does it yield a reference along with creating an object?

Similar is the case with Classes.

obj=SomeClass() #obj is a reference to object created by SomeClass().

Does SomeClass() return a reference along with creating an object?

Because we can use both obj.method1() and SomeClass().method1 to call methods.

Upvotes: 2

Views: 86

Answers (1)

Jim Diamond
Jim Diamond

Reputation: 1274

I suggest you reading The Python Language Reference "Data Model".

In python, when you create an object, it's being allocated in heap. If you assign your object to some variable, you actually are tagging it. One object may have many tags. When object looses all tags it may be destroyed by python garbage collector. So, an answer to your question -- [1,2,3] does not return any references, but simply creates new object.

EDIT:

Actually, during

[1, 2, 3].sort()

There is a reference to [1, 2, 3] list, that stays in VM's stack. But, as said before, it's not returned. But during:

l = [1, 2, 3]

This reference is copied from VM's stack to l.

Upvotes: 3

Related Questions