How to compare type of an object in Python?

后端 未结 14 2363
闹比i
闹比i 2020-11-28 01:26

Basically I want to do this:

obj = \'str\'
type ( obj ) == string

I tried:

type ( obj ) == type ( string )
<
相关标签:
14条回答
  • 2020-11-28 02:16

    isinstance works:

    if isinstance(obj, MyClass): do_foo(obj)
    

    but, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.

    EDIT: For the None type, you can simply do:

    if obj is None: obj = MyClass()
    
    0 讨论(0)
  • 2020-11-28 02:18

    It is because you have to write

    s="hello"
    type(s) == type("")
    

    type accepts an instance and returns its type. In this case you have to compare two instances' types.

    If you need to do preemptive checking, it is better if you check for a supported interface than the type.

    The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.

    For example, suppose you have this code

    def firstElement(parameter):
        return parameter[0]
    

    Now, suppose you say: I want this code to accept only a tuple.

    import types
    
    def firstElement(parameter):
        if type(parameter) != types.TupleType:
             raise TypeError("function accepts only a tuple")
        return parameter[0]
    

    This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be

    def firstElement(parameter):
        if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
            raise TypeError("interface violation")
        return parameter[0]
    

    but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:

    def firstElement(parameter):
        if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
            raise TypeError("interface violation")
        os.system("rm file")
        return parameter[0]
    

    in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.

    0 讨论(0)
提交回复
热议问题