Play Python test whether an object is a class string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.