Style question - defining immutable class data members

Terry Reedy tjreedy at udel.edu
Sat Mar 14 16:36:50 EDT 2009


Maxim Khitrov wrote:

> Perhaps a different example would help explain what I'm trying to do:
> 
> class Case1(object):
> 	def __init__(self):
> 		self.count = 0
> 		self.list  = []
> 
> 	def inc(self):
> 		self.count += 1
> 		self.list.append(self.count)
> 
> 	def val(self):
> 		return (self.count, self.list)

OK, so .count and .list (BAD IDEA TO USE BUILT-IN NAME)  are not 
constants, as you previously implied.

> 
> class Case2(object):
> 	count = 0
> 	list  = []
> 
> 	def inc(self):
> 		self.count += 1
> 		self.list.append(self.count)
> 
> 	def val(self):
> 		return (self.count, self.list)
> 
> for i in xrange(10):

You really only need one value of i for a test.  But you need multiple 
instances of each class

> 	c1 = Case1()
> 	c2 = Case2()

	c1a, c1b = Case1(), Case1()
	c2a, c2b = Case2(), Case2()

> 	for j in xrange(i):
> 		c1.inc()
> 		c2.inc()

		c1a.inc(), c1b.inc()
		c2a.inc(), c2b,inc()
> 
> 	v1, l1 = c1.val()
> 	v2, l2 = c2.val()

	print(c1a.val(), c1b.val(), c2a.val(), c2b.val())
> 
> 	print v1 == v2, l1 == l2

	# just look as all four tuples
> 
> The only difference between Case1 and Case2 classes is where the count
> and list attributes are defined.

and that 'only difference makes a major difference.  Make two instances 
of each class and you will see how.

Terry Jan Reedy





More information about the Python-list mailing list