文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [2004-08-11 17:33:30]

1. 测试是否一个对象是类似的string

3.3 Testing if an Object Is String-Like

测试是否一个对象是类似的string

Credit: Luther Blissett

1.1. 问题 Problem

You need to test if an object, typically an argument to a function or method you're writing, is a string (or more precisely, whether the object is string-like).

你需要去测试是否一个对象,典型的一个函数的参数或者你正在写的一个方法,是一个string(或 者更准确的说,是否一个对象是一个类sting的)

1.2. 解决 Solution

The first thing that comes to mind is type-testing:

出现在脑子里的第一个念头是类型测试:

   1 def isAString(anobj): return type(anobj) is type('')

However, this approach is not appropriate, as it wilfully destroys one of Python's greatest strengths梥mooth, signature-based polymorphism. Using the isinstance built-in function, which can accept a type argument in Python 2.0 or later, is only marginally better:

然而,这个方法不合适。因为它破坏了python最伟大的力量之一,基于签名的多态。使用内建函数 isinstance,在python2.0或者以后,它能接受一个类型参数,是更好的:

   1 def isAString(anobj): return isinstance(anobj, type(''))

This does accept instances of subclasses of type str (in Python 2.2 or better), but it still miserably fails to accept such clearly string-like objects as instances of UserString.UserString and Unicode strings. What you really want is a way to check if some object is string-like (i.e., whether it behaves like a string):

它接受类型str(在python2.2或以后)的子类的实例。但是它接受那样清晰的类string对象作为Us erString的实例仍然悲惨的失败了。UserString和Unicode strings。你想要的是一种检查是否一些对象是类sting的方法(也就是说,是否它的行为象string ):

   1 def isStringLike(anobj):
   2     try: anobj + ''
   3     except: return 0
   4     else: return 1

1.3. 讨论 Discussion

If it walks like a duck, and quacks like a duck, it's duck-like enough for our purposes. The isStringLike function in this recipe goes only as far as the "quacks like" part, but that's still far better than the disastrous attempts at rigorous duckhood-checking in the two unacceptable functions named isAString in the solution. It's easy to test a few more properties by using a richer expression in the try clause, if and when you need to check for more string-like features of the object anobj. For example:

如果它走起来象鸭子,并且叫声也象鸭子,那么它是足够象鸭子的。在这个配方的isStringLike函 数仅仅象鸭子那样叫。但是那仍然比在这个解决方案的命名为isAString的两个不可接受的函数中?br>业某⑹詃uckhood-checking要好的多。如果并且当你需要去为更多的对象anobj的类string特性?br>黾觳槭保ü趖ry子句里使用更丰富的表达式很容易去测试更多的属性。例如:

   1 try: anobj.lower( ) + anobj + ''

But in my experience, the simple test shown in the solution usually does exactly what I need.

但是在我的经验里, 在方案里简单的测试经常就是我需要的。

The most Pythonic approach to type validation (or any validation task, really) is to try to perform whatever task you need to do, detecting and handling any errors or exceptions that might result if the situation is somehow invalid. try/except works very well for this. Sometimes, as in this recipe, you may choose some simple task, such as concatenating to the empty string, as a stand-in for a much richer set of properties (such as all the various operations and methods available on string objects).

大部分python化的类型确认(或者任何确认任务)方法试图去执行你所需要去做的无论什么任务, 如果情况有一些不妙,发现并且处理任何错误或者异常可能的结果。try/except为它工作的非常好 。有时候,象在这个配方里一样,你可以选择一些简单的任务,例如连接到空的string,作为一个 更丰富的属性集合的替代(诸如所有的变量操作和方法在string对象上都可利用)

1.4. 参考 See Also

Documentation for the built-in functions isinstance, type, and issubclass in the Library Reference.