[Tutor] Testing a variable for being a number, string or other object...

Marc Barry marc_barry at hotmail.com
Tue Aug 12 11:10:49 EDT 2003


I have done the following and it seems to solve all of my problems.  I use 
the isinstance function to check for an objects instance type.  If there are 
any downfalls to doing this, please let me know.  Here is the general 
concept of what I have done.

------------------------------------------------------------

from types import IntType
from types import StringType

class IntHolder:
	def __init__(self, an_int):
		if(isinstance(an_int, IntType)):
			self.__an_int = an_int
		else:
			raise TypeError("Not an int.")
	def __str__(self):
		return str(self.__an_int)

def check(must_be_an_int, must_be_a_string, must_be_an_IntHolder):
	if(not isinstance(must_be_an_int, IntType)):
		raise TypeError("Not an int.")
	elif(not isinstance(must_be_a_string, StringType)):
		raise TypeError("Not a string.")
	elif(not isinstance(must_be_an_IntHolder, IntHolder)):
		raise TypeError("Not an IntHolder.")
	else:
		print must_be_an_int
		print must_be_a_string
		print must_be_an_IntHolder

new_holder = IntHolder(10)

check(10, "Hello", new_holder)

-------------------------------------------------------

Regards,

Marc



From: "Marc Barry" <marc_barry at hotmail.com>
To: tutor at python.org
Subject: [Tutor] Testing a variable for being a number,string or other 
object...
Date: Tue, 12 Aug 2003 09:22:12 -0400

Dear All:

My first question is how do I test if a variable is a number or a string?  I 
need to to do this for error checking on values passed into methods.

The second question I have is does Python have a way of testing for 
instances like Java does?  For example, the "instanceof" operator that lets 
you determine if an instance is of a certain type?

Regards,

Marc

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*   
http://join.msn.com/?page=features/junkmail


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8.  
http://join.msn.com/?page=features/junkmail




More information about the Tutor mailing list