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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • consternation

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

    I can't find neither in tutorial nor with google It's all about
    isinstance, or __class__.
    How to test that an object is an instance of my X class??
    Do I have this problems because I stre my objects in a dict?

    I wrote a class X like this :
    class X(object):

    def __init__(self,n ame):
    self.name=name
    self.val=[]
    self.descriptio n ="class X contains : "

    def __repr__(self):
    for i in range(len(self. val)):
    description+=i
    return self.descriptio n


    In class Y I create my X objects and put them into a dict

    print "\nTEST"
    ..for (i,v) in self.mem.items( ):
    print v

    The objects are printed out the way I specified in __repr__, so I know it's
    an object of X class.
    No I want to put in the dict some other objects of class Z,K....
    When I get the value fom dict I have to distinguish them somehow to handle
    them latr in programm.
    I thouth about isinstanceof - it doesn't work. I did some tests, but I
    don't understand the answers:
    Why python claims it's a list, but still print's it like X class
    #in Y class:
    print isinstance(v,X) False
    print v.__class__.__n ame__ list


    And adding print in X class i see
    def __repr__(self):
    print self.__class__ -- [__main__.Comple x

    Could someone explain this to me?
    thank you


  • paul.keating@nibc.com

    #2
    Re: newbee I have an object how to check what's his class?

    This doesn't answer your whole post because it asked a lot of
    questions. But as to finding out whether something is an instance of a
    class:

    class X(object):
    # ... defined as in your post
    >>x = X('Fred')
    >>x
    class X contains:
    >>type(x) is X
    True
    >>isinstance(x, X)
    True
    >>x.__class__._ _name__
    'X'

    Now for subclasses:

    class Y(X):
    extrastuffinY = 1
    >>y = Y('Joe')
    >>type(y) is X
    False
    >>isinstance(y, X)
    True


    consternation:
    I can't find neither in tutorial nor with google It's all about
    isinstance, or __class__.
    How to test that an object is an instance of my X class??

    Comment

    • consternation

      #3
      Re: newbee I have an object how to check what's his class?

      Thank You for reply but ....
      I found solution suggested by You in a tutorial yesterday. For some reason
      it doesn't work in my case.

      code:
      #mem-dictionary in Y class for storing objects
      #Y doesn't inherit from X
      for (i,v) in self.mem.items( ):
      print " isinstance(x,X) "
      print isinstance(v,X)
      print "type(x) is X"
      print type(v) is X
      print v.__class__.__n ame__
      print v.__class__

      result:
      isinstance(x,X)
      False
      type(x) is X
      False
      <type 'list'>
      list

      Well I can handle my problem. I will give an extra field in class with it's
      name. But I thought that when a language has tools to learn a class of an
      object one should use it.


      paul.keating@ni bc.com wrote:
      This doesn't answer your whole post because it asked a lot of
      questions. But as to finding out whether something is an instance of a
      class:
      >
      class X(object):
      # ... defined as in your post
      >
      >>>x = X('Fred')
      >>>x
      class X contains:
      >>>type(x) is X
      True
      >>>isinstance(x ,X)
      True
      >>>x.__class__. __name__
      'X'
      >
      Now for subclasses:
      >
      class Y(X):
      extrastuffinY = 1
      >
      >>>y = Y('Joe')
      >>>type(y) is X
      False
      >>>isinstance(y ,X)
      True
      >
      >
      consternation:
      >
      >I can't find neither in tutorial nor with google It's all about
      >isinstance, or __class__.
      >How to test that an object is an instance of my X class??

      Comment

      • Marc 'BlackJack' Rintsch

        #4
        Re: newbee I have an object how to check what's his class?

        In <ej2b34$9nk$1@u ltra60.mat.uni. torun.pl>, consternation wrote:
        Thank You for reply but ....
        I found solution suggested by You in a tutorial yesterday. For some reason
        it doesn't work in my case.
        >
        code:
        #mem-dictionary in Y class for storing objects
        #Y doesn't inherit from X
        for (i,v) in self.mem.items( ):
        print " isinstance(x,X) "
        print isinstance(v,X)
        print "type(x) is X"
        print type(v) is X
        print v.__class__.__n ame__
        print v.__class__
        >
        result:
        isinstance(x,X)
        False
        type(x) is X
        False
        <type 'list'>
        list
        Define "doesn't work". Obviously lists are not instances of your `X`
        class. So where's the problem? What did you expect and why?

        Ciao,
        Marc 'BlackJack' Rintsch

        Comment

        • consternation

          #5
          Re: newbee I have an object how to check what's his class?


          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>
          <a2 <\a>

          <X id="1">
          <a>3 <\a>
          <b4<\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/Coo...n/Recipe/66516
          def addItem(self,wo rd,pagenumber):
          self.mem.setdef ault(word,[]).append(pagenu mber)
          ^^^^^^^^
          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>
          <a4<\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__.__na me__
          and results
          <class X<----no [!!!!
          <a>1<\a>
          <a>2<\a>
          <class X>
          <a >3<\a>
          <a4<\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 :-)


          Comment

          • Gabriel Genellina

            #6
            Re: newbee I have an object how to check what's his class?

            At Friday 10/11/2006 18:05, consternation wrote:
            >def __init__
            self.mem={}
            >I googled a way how to add elements to dict, I have read the code not the
            >description below
            self.mem[key] = value

            I strongly suggest you read some introductory Python docs, like
            http://docs.python.org/tut/tut.html or http://www.diveintopython.org
            >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.
            You still didn't show enough code, but I bet that X is an old-style
            class, that is, you wrote:
            class X: blablabla
            instead of
            class X(object): blablabla
            For old-style class instances, type(x) is InstanceType, not the actual class.


            --
            Gabriel Genellina
            Softlab SRL

            _______________ _______________ _______________ _____
            Correo Yahoo!
            Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
            ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar

            Comment

            Working...