473,800 Members | 2,541 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
Nov 10 '06 #1
5 1313
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??
Nov 10 '06 #2
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.
pa**********@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??
Nov 10 '06 #3
In <ej**********@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
Nov 10 '06 #4

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 :-)
Nov 10 '06 #5
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
Nov 10 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1662
by: Newbee Adam | last post by:
some said that .NET app can run on any program where rutime exists. What is "runtime" in this sense? will I have to install runtime or .net framework or .NET support on an xp machine for a .NET app to work? keep in mind I am a newbee :-) !! thanks --
3
1284
by: Kiran | last post by:
Hi, I am new to dotNet, as my background is from Delphi, I am always looking for the way to do it that way :) sorry abt that. I was looking for a way to delegate the interface supported by my class to one of the contained class which we can do in Delphi using "implements" keyword. OK to be more specific here is an example Class CX : IX; and
2
1552
by: Visual Systems AB \(Martin Arvidsson\) | last post by:
Hi! I was testing an application that is writing a mail and sends it to a recieptiens. I then came across a couple of ??? in my head, coul anyone briefly tell me what the difference is between this and where in the help i can read more about it First out... Outlook.Application oApp = new Outlook.Application();
1
1239
by: Visual Systems AB \(Martin Arvidsson\) | last post by:
Doesn't Visual Studio Enterprise 2003 come with components for file and directory browsing? This simple thing was included in Delphi 2005... Regards Martin Arvidsson
5
1251
by: DotNet | last post by:
I'm trying to construct a header user control and would like to pass an integer to the control in order to display the correct on state for a menu. How does one pass an integer from an .aspx page to an .ascx page when the page loads? Thanks.
4
1189
by: John please don't spam me! | last post by:
Hi Guys, I writing a project with just one module in it (the reason for this is to debug code before it becomes a service) and am getting an error which I do not understand: No accessible 'Main' method with an appropriate signature was found in 'FTP_Log_Watcher'. I have set the properties of FTP_Log_Watcher to Startup with 'Sub Main'.
8
1382
by: ikarias | last post by:
Maybe not the right place to aske this, but a newbee (me) needs help. i trying to input a number into a textbox, so i can make a series of calculations. in the old days of basic i just jused nrstring=val(input) , but life isnt as easy anymore. I brewed something together as a test, but it failes on me. Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ...
4
1636
by: registration | last post by:
I need to copy a LPOLESTR to another LPOLESTR for later usage. I do the following while inside a CreateClassEnumerator loop : LPOLESTR lpDisplayName; pMoniker->GetDisplayName(NULL, NULL, &lpDisplayName); I need to create a copy of lpDisplayName to store inside a class for later reference.
2
1730
by: Rene | last post by:
Hello to all! I am a newbee to C++, I did a beginners' course, and now I am stuck with a strange problem. I have written the function that is pasted downwards. The peculiar thing is that when I sent the function the value "0", the .lst file is created properly (the vector I am using/saving is made up of structs of one AnsiString (using BCB) called "naam" and one int called "nummer", I guess You'll get what they mean in English ;-))....
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10274
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.