Accessing an instance of a class from within instance of another class

2010-04-30 Thread Stefan Krastanov
Hello all,

I have some knowledge of programing in C++ and I believe that I understand
the way one should write programs in Python. But I need some help finding
the Right Way for doing a thing.

Here is the problem:
I have a class (call it Data) that has a number of NumPy arrays and some
methods that get useful information from the arrays (math stuff).
I have two other classes (called Viewer1 and Viewer2) (they are subclasses
of QAbstractTableModel but that's not important).
I am working in my code with one instance of each class. Viewer1 and Viewer2
must be able to call methods from the Data instance, but as the instance of
Data is constantly updated, I cannot just copy it.
I have thought of the following solution:

data = Data()

class Viewer(***):
def __init__(self, ***, data):
***
self.D = [data, ]

def Data(self):
return self.D[0]

def SomeOtherFunction(self):
 self.Data.something()

It's an ugly way to implement a pointer or something like it. What is the
right way?

Cheers
Stefan Krastanov

P.S. Maybe it's bad idea to use two different view classes, but that is
another question.
P.P.S. Maybe I'm breaking the encapsulation. What should I do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing an instance of a class from within instance of another class

2010-04-30 Thread Paul Kölle

Am 30.04.2010 13:05, schrieb Stefan Krastanov:

Hello all,


[snipp]


Here is the problem:
I have a class (call it Data) that has a number of NumPy arrays and some
methods that get useful information from the arrays (math stuff).
I have two other classes (called Viewer1 and Viewer2) (they are subclasses
of QAbstractTableModel but that's not important).
I am working in my code with one instance of each class. Viewer1 and Viewer2
must be able to call methods from the Data instance, but as the instance of
Data is constantly updated, I cannot just copy it.
Why do you think the data is copied? Both viewers will hold a reference 
to the same data object:


Type help, copyright, credits or license for more information.
 class d(object):
...   a = 1
...   b = 2
...   c = 3
...
 d1 = d()
 d1.a
1
 class view1(object):
...   def __init__(self, data):
... self.data = data
...   def data(self):
... return self.data
...
 class view2(object):
...   def __init__(self, data):
... self.data = data
...   def data(self):
... return self.data
...
 v1 = view1(d1)
 v2 = view2(d1)
 v2.data.b
2
 v2.data.b = 4
 v2.data.b
4
 v1.data.b
4


hth
 Paul




--
http://mail.python.org/mailman/listinfo/python-list