python - How to make two classes sharing a same attribute? -


i have defined class posseses attribute score matrix. let's var instance of class.

i have class needs access 1 particular cell of matrix var.score. :

class myclass:     def __init__(self, r, c):         self.cell = var.score[r][c]     ...     # make operations on self.cell 

except if self.cell modified, modification should reflect on var.score[r][c]. goal of creating self.cell , not using var.score[r][c] clarity , avoiding dragging r , c along following definition of class.

i've seen solutions using wrapper mutable objects list didn't satisfied me. best solution implement ?

you use property:

class foo(object):     def __init__(self, r, c):         self.r = r         self.c = c      @property     def cell(self):         return var[self.r][self.c]      @cell.setter     def cell(self, val):         var[self.r][self.c] = val 

then:

>>> var = [[1, 2], [3, 4]] >>> x = foo(0, 1) >>> x.cell 2 >>> x.cell = 8 >>> var [[1, 8], [3, 4]] >>> y = foo(1, 1) >>> y.cell = 88 >>> var [[1, 8], [3, 88]] >>> var[0][1] = "hello" >>> x.cell 'hello' 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

how to prompt save As Box in Excel Interlop c# MVC 4 -

xslt 1.0 - How to access or retrieve mets content of an item from another item? -