Accessor class peer review

D-Man dsh8290 at rit.edu
Wed Jan 3 14:04:06 EST 2001


Hi all.  I did some work on a template for an Accessor class based on
the ideas presented by Alex in an earlier thread.  I would like to
hear people's opinions regarding this code.  (I'm not interested in
comments such as 'clients should explicitly call mutator/accessor
functions').

I added a level of granularity to it so that the class can specify
which members clients can access (the ones with _set* or _get*
functions) and which ones only the class itself is allowed to acccess
(__set* and __get*).


Thanks for the comments,
-D

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Access :
	def __setattr__( self , name , value ) :
		# when the mutator tries to assign the value, __setattr__ will
		# be called again,

		# first check to see if the name is the mangled name from the
		# mutator
		if name.startswith( "_" + self.__class__.__name__ + "_" ) :
			self.__dict__[ name ] = value
		# otherwise find the mutator method and call it
		else :
			mutator = getattr( self , "_set_" + name , None )
			if mutator is None :
				msg = "Mutation of instance member '" 
				msg += name + "' denied"
				raise AttributeError( msg )

			mutator( value )
	
	def __getattr__( self , name ) :
		# this happens if the instance's attribute DNE yet, but
		# __setattr__ want's to assign to it
		if name.startswith( "_set__" + self.__class__.__name__ ) :
			self.__dict__[ name ] = None

		# if the name starts with "_get_" the method DNE,
		# stop recursion
		elif name.startswith( "_get_" ) :
			# remove the tricky prefix before throwing the exception
			msg = "Instance member '" + name[5:] + "' "
			msg += "DNE or Access Denied"
			raise AttributeError( msg )

		# otherwise it is normal, find the accessor and return its
		# return value
		else :
			accessor = getattr( self , "_get_" + name )
			return accessor()
	
	def _set_good( self , value ) :
		"""The public mutator."""
		self.__set_good( value )
	
	def _get_good( self ) :
		"""The public accessor."""
		return self.__get_good()

	def __set_good( self , value ) :
		"""The private mutator, does the "real" work."""
		self.__good = value
	
	def __get_good( self ) :
		"""The private accessor, does the real work."""
		return self.__good
	

# to test
if __name__ == "__main__" :
	print

	obj = Access()

	# assign a mutatable member
	obj.good = "Hello World of good OO\n"

	# print an accessible member
	print obj.good

	# assign a immutatable member
	try :
		obj.bad = "This is an error!"
	except AttributeError , e :
		print "AttributeError:" , e
		print
		
	# print an inaccessible member
	try :
		print obj.bad
	except AttributeError , e :
		print "AttributeError:" , e
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




More information about the Python-list mailing list