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

Paul Kölle paul at subsignal.org
Fri Apr 30 10:17:38 EDT 2010


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







More information about the Python-list mailing list