के सभी परिवर्तनों का पता लगाता है मेरे पास दो संपत्तियां हैं जिनमें सूचियां हैं। जब भी इस सूची में कोई भी आइटम बदलता है, तो मैं दूसरी सूची को स्वयं अपडेट करना चाहता हूं। इसमें स्टेटमेंट obj.myProp [3] = 5 शामिल है। अभी, यह कथन पूरी सूची प्राप्त करने के लिए गेटर फ़ंक्शन को कॉल करता है, सूची से तीसरा आइटम प्राप्त करता है, और इसे 5 पर सेट करता है। मेरीप्रॉप सूची बदल दी जाती है, लेकिन दूसरी सूची कभी अपडेट नहीं होती है।पायथन: एक संपत्ति और एक सेटर फ़ंक्शन के साथ कैसे है जो
यहाँ मेरी कोड
class grid(object):
def __init__(self,width=0,height=0):
#make self._rows a multi demensional array
#with it's size width*height
self._rows=[ [None]*height for i in xrange(width) ]
#make self._columns a multi demensional array
#with it's size height*width
self._columns=[ [None]*width for i in xrange(height) ]
@property
def rows(self):#getting the rows of the array
return self._rows
@rows.setter
def rows(self,value):#when the rows are changed, the collumns are updated.
self._rows=value
self._columns=self._flip(value)
@property
def columns(self):#getting the columns of the array
return self._columns
@columns.setter
def columns(self,value):#when the columns are changed, the rows are updated
self._columns=value
self._rows=self._flip(value)
@staticmethod
def _flip(args):#this flips the array
ans=[ [None]*len(args) for i in xrange(len(args[0])) ]
for x in range(len(args)):
for y in range(len(args[0])):
ans[y][x] = args[x][y]
return ans
है और यहाँ एक उदाहरण रन है।
>>> foo=grid(3,2)
>>> foo.rows
[[None, None], [None, None], [None, None]]
>>> foo.columns
[[None, None, None], [None, None, None]]
>>> foo.rows=[[1,2,3],[10,20,30]]
>>> foo.rows
[[1, 2, 3], [10, 20, 30]]
>>> foo.columns
[[1, 10], [2, 20], [3, 30]]
>>> foo.rows[0][0]=3
>>> foo.rows
[[3, 2, 3], [10, 20, 30]]
>>> foo.columns
[[1, 10], [2, 20], [3, 30]]
अगर आप पिछले तीन लाइनों को देखो, इस जहां वास्तविक समस्या तब होती है है। मैंने sublist का पहला आइटम तीन तक सेट किया है, लेकिन foo.columns ने अपनी सूची में 3 को रखने के लिए कभी भी अपडेट नहीं किया है।
इसलिए संक्षेप में, मैं एक वैरिएबल कैसे बना सकता हूं जो हमेशा एक और चर अद्यतन करता है, भले ही यह सबिटैम बदला जा रहा हो।
मैं अजगर 2.7