Python type() or __class__, == or is

前端 未结 4 600
萌比男神i
萌比男神i 2020-12-13 03:41

I want to test whether an object is an instance of a class, and only this class (no subclasses). I could do it either with:

obj.__class__ == Foo
obj.__class_         


        
4条回答
  •  抹茶落季
    2020-12-13 04:02

    Update: Thanks all for the feedback. I'm still puzzled by whether or not class objects are singletons, my common sense says they are, but it's been really hard to get a confirmation (try googling for "python", "class" and "unique" or "singleton").

    I can confirm that __instance__ is a singleton. Here is the proof.

    >>> t1=File.test()
    made class
    >>> t2=File.test()
    made class
    >>> print t1.__class__()
    made class
    
    >>> print t2.__class__()
    made class
    
    

    As you can see both t1 and t2 print out the same value in memory even though t1 and t2 are at different values in memory. Here is the proof of that.

    >>> print t1
    
    >>> print t2
    
    

    The __instance__ method only exists if you used class "name"(object):. If you use the classic style class, class "name":, than the __instance__ method doesn't exist.

    What this means is to be the most generic you probably want to use type unless you know for a fact instance does exist.

提交回复
热议问题