Referring to type testing, I first thought about the characteristics of the " Duck type " in Python, the so-called duck type, that is, if it walks like a duck, and the bark is like a duck,
So for our application, we can think of it as a duck! It's all for functional reuse.
We always need to test an object, especially when writing a function or method, it is often necessary to test whether the incoming parameter is a string;
The following method uses the built-in isinstance and basestring to quickly and easily check whether an object is a string or a Unicode object:
def is_string (anobj):
Return Isinstance (Anobj, basestring)
Many people see this method will be questioned and replaced by the following method, but unfortunately, the following methods have serious vulnerabilities:
def is_string (anobj):
return type (anobj) is type (")
The source of Python's power-a smooth, signature-based polymorphic mechanism tells us that this method sucks, and it's clear that the Unicode object
Can not pass this test, not to mention the user's own written str subclass;
The use of isinstance and basestring is much better, since STR and Unicode have a common base class, but there are still slips:
The above method is not applicable to the UserString class provided by the UserString module;
It suddenly reminds me of a famous way of dealing with problems, but also a guarantee of try/except tools: getting forgiveness After the event is always better than getting a prior permission,
It 's much easier (EAFP); So maybe we can do something ourselves:
def islikestring (anobj):
Try:anobj + "
Except:return False
Else:return True
Key words: Duck judgment, Eafp, Isinstance, basestring