Implementing pointers in Python

This is the place for queries that don't fit in any of the other categories.

Implementing pointers in Python

Postby Yuval » Wed Aug 14, 2013 11:25 am

Hey there,

Would appreciate very much help on this data structure issue:

I want to create an object of type "event" which will include for example the fields "bike", "station","time". My goal is to keep each object of this class only once in the computer's memory but to be part of two different lists - one of a certain value of "bike" and one of a certain value of "station". Like using pointers in C.

an illustration is provided as attachment.

A huge thanks in advance,

Yuval.
Attachments
Data structure illustration.png
Data structure illustration.png (10.81 KiB) Viewed 120 times
Yuval
 
Posts: 1
Joined: Wed Aug 14, 2013 11:03 am

Re: Implementing pointers in Python

Postby stranac » Wed Aug 14, 2013 12:10 pm

If you store the same object in two different lists, it won't be stored twice in memory.
Both lists will contain a reference to the same object.

I have no idea what the picture is supposed to mean...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 897
Joined: Thu Feb 07, 2013 3:42 pm

Re: Implementing pointers in Python

Postby Mekire » Wed Aug 14, 2013 12:12 pm

If you put an instance of a class in two different lists, there is still only one object. If you change one you change the other. Everything in python is a reference; the distinction is just mutable and immutable.

Code: Select all
class MyClass(object):
    def __init__(self,x):
        self.x = x

    def __repr__(self):
        return "MyClass({})".format(repr(self.x))


some_instance = MyClass(0)
a = [some_instance,5,"spam"]
b = ["something","nothing",some_instance]

print(a)
print(b)

a[0].x = "Wow, I changed in both lists."

print(a)
print(b)
Code: Select all
>>>
[MyClass(0), 5, 'spam']
['something', 'nothing', MyClass(0)]
[MyClass('Wow, I changed in both lists.'), 5, 'spam']
['something', 'nothing', MyClass('Wow, I changed in both lists.')]
>>>

As you can see changing it in one changed the corresponding one in the other.
-Mek

Edit: Simplified.
User avatar
Mekire
 
Posts: 818
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 4 guests

cron