473,320 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Trying to generate a list of the subclasses of C

List:

I have this:

# classC.py

class C(object): pass

class D(C): pass

class E(C): pass

def CSubclasses():
for name in dir(): pass

I'm trying to create a list of all of C's subclasses:

import classC

print C
aList = []
for name in dir(classC):
print name,
try:
if issubclass(classC.__dict__[name], C):
print classC.__dict__[name]
else:
print
except TypeError:
print

Which gives me this:

<class '__main__.C'>
C
CSubclasses
D
E
__builtins__
__doc__
__file__
__name__

However when I do this from the command line:
issubclass(D,C) True

but
issubclass(classC.__dict__['D'], C)

False

So my approach is flawed.

The end result I'm after is an automatically generated dictionary
containing instaces of the subclasses keyed by the subclass names:

{'D':D(), 'E':E(), . . . }

I can see the information I need in the module's __dict__ and by using
the dir() method, but I'm not having much success extracting it.

Jan 16 '06 #1
5 1254
> The end result I'm after is an automatically generated dictionary
containing instaces of the subclasses keyed by the subclass names:

{'D':D(), 'E':E(), . . . }

I can see the information I need in the module's __dict__ and by using
the dir() method, but I'm not having much success extracting it.


Use a metaclass:
subclassesofc = []

class SubclassCollector(type):

def __new__(cls, name, bases, dict):
subclassesofc.append(name)
return type.__new__(cls, name, bases, dict)

class C(object):
__metaclass__ = SubclassCollector

class A(C):
pass

print subclassesofc

Regards,

Diez
Jan 16 '06 #2
Charles Krug a écrit :
List:

I have this:

# classC.py

class C(object): pass

class D(C): pass

class E(C): pass

def CSubclasses():
for name in dir(): pass

I'm trying to create a list of all of C's subclasses:

import classC

print C
aList = []
for name in dir(classC):
print name,
try:
if issubclass(classC.__dict__[name], C):
print classC.__dict__[name]
else:
print
except TypeError:
print

Where is C defined ?
import classC

does not define the name C in the current scope ... thus, you should write :

for name in dir(classC):
print name,
try:
if issubclass(classC.__dict__[name], classC.C):
print classC.__dict__[name]
else:
print
except TypeError:
print

and it gives :

C <class 'test_subclass.C'>
CSubclasses
D <class 'test_subclass.D'>
E <class 'test_subclass.E'>
__builtins__
__doc__
__file__
__name__

.... which is exactly what you want !

Pierre
Which gives me this:

<class '__main__.C'>
C
CSubclasses
D
E
__builtins__
__doc__
__file__
__name__

However when I do this from the command line:

issubclass(D,C)
True

but

issubclass(classC.__dict__['D'], C)


False

So my approach is flawed.

The end result I'm after is an automatically generated dictionary
containing instaces of the subclasses keyed by the subclass names:

{'D':D(), 'E':E(), . . . }

I can see the information I need in the module's __dict__ and by using
the dir() method, but I'm not having much success extracting it.

Jan 16 '06 #3
Charles Krug wrote:
The end result I'm after is an automatically generated dictionary
containing instaces of the subclasses keyed by the subclass names:

{'D':D(), 'E':E(), . . . }

I can see the information I need in the module's __dict__ and by using
the dir() method, but I'm not having much success extracting it.


Try this:

class C(object): pass

class D(C): pass

class E(C): pass

def CSubclasses():
return dict((cls.__name__, cls) for cls in C.__subclasses__())

print CSubclasses()
Jan 16 '06 #4
Charles Krug <cd****@aol.com> wrote:
...
I'm trying to create a list of all of C's subclasses:


There's a class method for that very purpose:
class C(object): pass .... class D(C): pass .... class E(C): pass .... C.__subclasses__() [<class '__main__.D'>, <class '__main__.E'>]

Alex
Jan 16 '06 #5
On 2006-01-16, Alex Martelli <al***@mail.comcast.net> wrote:
Charles Krug <cd****@aol.com> wrote:
...
I'm trying to create a list of all of C's subclasses:


There's a class method for that very purpose:
class C(object): pass ... class D(C): pass ... class E(C): pass ... C.__subclasses__() [<class '__main__.D'>, <class '__main__.E'>]

Alex


Exactly what I was looking for, thanks.

It stuck in my brain that there was a way to do this, but I couldn't lay
my mouse on it.

Jan 19 '06 #6

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

Similar topics

1
by: Edward Loper | last post by:
I'm having trouble pickling subclasses of dict when they contain cycles. In particular: >>> import pickle >>> class D(dict): pass >>> d = D() >>> d = d # add a cycle. >>> print d {1: {...}}...
30
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course,...
0
by: Vera | last post by:
Hi, I have a very annoying problem, with which I NEED HELP DESPERATELY!! It smells like a bug to me, but I'm not sure. SITUATION This description is a very much simplified version of the real...
4
by: spike | last post by:
I've googled like crazy and can't seem to find an answer to why this isn't working. I want to create a custom list class that acts as a circular list. ie: my_list = (0, 1, 2) how I want it...
9
by: Henk Verhoeven | last post by:
We are not alone! "Where other MDA tools are generating programmingcode, Codeless chooses not to generate code at all". OK, phpPeanuts is not an MDA tool (it has no fancy modeling GUI). But it...
11
by: hazz | last post by:
before I start filling up the first page of perhaps many pages of code with if/then or switch:case buckets, I wanted to step back and see if there is a better way... I will have a table with up to...
1
by: Bruce HS | last post by:
I'm using VS2005, VB, WinForms I’ve developed forms using those nice wizards Microsoft provides. However, I’m running into a couple of complications trying to work with the resulting Table...
4
by: bob_jeffcoat | last post by:
Hi, Have class B which subclasses from class A. I have a List<B> and I'm trying to get a List<A> without writing a stupid loop everytime I want to do it. So I tried this method: public...
6
by: Osiris | last post by:
Is the following intuitively feasible in Python: I have an array (I come from C) of identical objects, called sections. These sections have some feature, say a length, measured in mm, which is...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.