newbee I have an object how to check what's his class?

consternation copiernik at wp.pl
Fri Nov 10 16:05:16 EST 2006


I think I know now where my problems come from. I spare you boring 
implementation code.
The case look like this: I parse xml file something a like
 <X id="0">
    <a>1   <\a>
    <a> 2  <\a>

    <X id="1">
        <a>3 <\a>
        <b> 4<\b>
    <\X>
</X>

<X id="2">
    <a>   <\a>
    <a>   <\a>

    <X id="3">
        <a> <\a>
        <b> <\b>
    <\X>
</X>
I  succesfully constructlop-level X objects - I see all components when i 
print X0, X1 out with _repr_.
I store my X's in memory. I had some problems with this. I googled, red 
newsgoup ad foud a solution that seemd to be perfect for me (...till now). 
In the parser- Y class a have a dictionary
def __init__
 self.mem={}
I googled a way how  to add elements to dict,  I have read the code not the 
description below
##copied from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66516
   def addItem(self,word,pagenumber):
        self.mem.setdefault(word,[]).append(pagenumber)
                                   ^^^^^^^^
So my dict looks like{
(id of top-level X)  0 :  (the X itself) X0,
            2     :    X2,
            4..........
}
I wrote it some time and I was tired I haven't pay attention to  the 
breackets at he beginning of outprint
TOP LEVEL X WITH ID=0
[<class  X> <----
<a>1<\a>
<a>2<\a>
        <class  X>
        <a >3<\a>
        <a> 4<\a>
       <\class  X>
<\class  X>]
One can clearly see it's a list :( Shame on me.
I did a trick. If my X object is stored in a list and it's the only element 
of the list I can simply use it like:
                print v[0]
                print" isinstance(x,X)"
                print isinstance(v[0],X)
                print "type(x) is X"
                print type(v[0]) is X
                print v[0].__class__
                print v[0].__class__.__name__
and results
<class  X> <----no [!!!!
<a>1<\a>
<a>2<\a>
        <class  X>
        <a >3<\a>
        <a> 4<\a>
       <\class  X>
<\class  X>

isinstance(x,X)
True                :-)
type(x) is X
False                :( ??
__main__.X
X
 temporarily it solves my probblems I'm just curious why type can't handle 
the test.
Thank you for help, and making me think :-) 





More information about the Python-list mailing list