Binding a variable?

Paul Dale pd at traxon.com
Mon Oct 24 03:15:36 EDT 2005


Thanks everyone for your comments and suggestions!

I haven't quite decided which approach I'll take, but it's nice to have 
some options.

Paul

Tom Anderson wrote:

>On Fri, 21 Oct 2005, Paul Dale wrote:
>
>  
>
>>Is it possible to bind a list member or variable to a variable such that
>>
>>temp = 5
>>list = [ temp ]
>>temp == 6
>>list
>>
>>would show
>>
>>list = [ 6 ]
>>    
>>
>
>As you know by now, no. Like any problem in programming, this can be 
>solved with a layer of abstraction: you need an object which behaves a bit 
>like a variable, so that you can have multiple references to it. The 
>simplest solution is to use a single-element list:
>
>  
>
>>>>temp = [None] # set up the list
>>>>temp[0] = 5
>>>>list = [temp]
>>>>temp[0] = 6
>>>>list
>>>>        
>>>>
>[[6]]
>
>I think this is a bit ugly - the point of a list is to hold a sequence of 
>things, so doing this strikes me as a bit of an abuse.
>
>An alternative would be a class:
>
>class var:
> 	def __init__(self, value=None):
> 		self.value = value
> 	def __str__(self): # not necessary, but handy
> 		return "<<" + str(self.val) + ">>"
>
>  
>
>>>>temp = var()
>>>>temp.value = 5
>>>>list = [temp]
>>>>temp.value = 6
>>>>list
>>>>        
>>>>
>[<<6>>]
>
>This is more heavyweight, in terms of both code and execution resources, 
>but it makes your intent clearer, which might make it worthwhile.
>
>tom
>
>  
>



More information about the Python-list mailing list