473,653 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

instantiate all subclasses of a class

What is the simplest way to instantiate all classes that are
subclasses of a given class in a module?

More precisely I have a module m with some content:

# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py

and then in another module I have currently:

# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py

and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.

Any ideas?
Jul 16 '06 #1
7 2071
In <ma************ *************** ************@py thon.org>, Daniel Nogradi
wrote:
More precisely I have a module m with some content:

# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py

and then in another module I have currently:

# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py

and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.

Any ideas?
Just go through the objects in the module, test if they are classes,
subclasses of `A` and not `A` itself:

from inspect import isclass
import test

instances = dict()
for name in dir(test):
obj = getattr(test, name)
if isclass(obj) and issubclass(obj, test.A) and obj is not test.A:
instances[name] = obj()

Jul 16 '06 #2
Daniel Nogradi wrote:
What is the simplest way to instantiate all classes that are
subclasses of a given class in a module?

More precisely I have a module m with some content:

# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py

and then in another module I have currently:

# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py

and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.

Any ideas?
It's pretty easy
import m
from inspect import getmembers, isclass, getmro

t = '%s = m.%s()'

for name, class_ in getmembers(m, isclass):
if class_ is m.A:
continue
if m.A in getmro(class_):
exec t % (name, name)
Peace,
~Simon

Jul 16 '06 #3
More precisely I have a module m with some content:

# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py

and then in another module I have currently:

# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py

and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.

Any ideas?

Just go through the objects in the module, test if they are classes,
subclasses of `A` and not `A` itself:

from inspect import isclass
import test

instances = dict()
for name in dir(test):
obj = getattr(test, name)
if isclass(obj) and issubclass(obj, test.A) and obj is not test.A:
instances[name] = obj()

Thanks, this looks pretty good. However there is some wierdness with
isclass: whenever a class has a __getattr__ method an instance of it
will be detected by isclass as a class (although it is not).
>>from inspect import isclass

class x:
.... def __getattr__( self, attr ):
.... pass
....
>>y = x( )
isclass( y )
True
>>>
If there is no __getattr__ method isclass works as expected. Am I
misunderstandin g something here or isclass should return False for any
instance of any class including those with a __getattr__ method?
Jul 16 '06 #4
Daniel Nogradi wrote:
Thanks, this looks pretty good. However there is some wierdness with
isclass: whenever a class has a __getattr__ method an instance of it
will be detected by isclass as a class (although it is not).
>from inspect import isclass

class x:
... def __getattr__( self, attr ):
... pass
...
>y = x( )
isclass( y )
True
Which reinforces Michael Spencer's instinct that the inspect.isclass ()
implementation is a bit too clever (see
http://mail.python.org/pipermail/pyt...y/351448.html).
If there is no __getattr__ method isclass works as expected. Am I
misunderstandin g something here or isclass should return False for any
instance of any class including those with a __getattr__ method?
It certainly should, and I believe that the obvious test

isinstance(obj, (types.ClassTyp e, type))

will work.

Peter
Jul 16 '06 #5
>>from inspect import isclass
>>>
>>class x:
... def __getattr__( self, attr ):
... pass
...
>>y = x( )
>>isclass( y )
True

Which reinforces Michael Spencer's instinct that the inspect.isclass ()
implementation is a bit too clever
Wouldn't the word 'broken' be more appropriate? :)
>
isinstance(obj, (types.ClassTyp e, type))
Thanks a lot this indeed works.
Jul 16 '06 #6
What is the simplest way to instantiate all classes that are
subclasses of a given class in a module?

More precisely I have a module m with some content:

# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py

and then in another module I have currently:

# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py

and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.

Any ideas?

It's pretty easy
import m
from inspect import getmembers, isclass, getmro

t = '%s = m.%s()'

for name, class_ in getmembers(m, isclass):
if class_ is m.A:
continue
if m.A in getmro(class_):
exec t % (name, name)
Actually, this variant also suffers from the broken isclass implementation.

(Simon, sorry for the double post.)
Jul 16 '06 #7
Daniel Nogradi wrote:
What is the simplest way to instantiate all classes that are
subclasses of a given class in a module?
>
More precisely I have a module m with some content:
>
# m.py
class A:
pass
class x( A ):
pass
class y( A ):
pass
# all kinds of other objects follow
# end of m.py
>
and then in another module I have currently:
>
# n.py
import m
x = m.x( )
y = m.y( )
# end of n.py
>
and would like to automate this in a way that results in having
instances of classes from m in n whose names are the same as the
classes themselves. But I only would like to do this with classes that
are subclasses of A.
>
Any ideas?
It's pretty easy
import m
from inspect import getmembers, isclass, getmro

t = '%s = m.%s()'

for name, class_ in getmembers(m, isclass):
if class_ is m.A:
continue
if m.A in getmro(class_):
exec t % (name, name)

Actually, this variant also suffers from the broken isclass implementation.

(Simon, sorry for the double post.)

Not a problem, I haven't used inspect much so I've not been bitten by
this bug before. It's good to know!

(I would have assumed that isclass() would have been implemented as
isinstance(obj, (types.ClassTyp e, type)) anyway. I'm surprised it's
not, and that it's so broken..)

Thanks.

Jul 16 '06 #8

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

Similar topics

2
2478
by: jerrygarciuh | last post by:
Hello, Is it possible to instantiate a child class within the constructor of its parent? eg Class DBI extends DB { function DBI() { // explicit parent constructor call
5
2893
by: Thomas Philips | last post by:
I'm teaching myself programming using Python, and have a question about subclasses. My game has two classes, Player and Alien, with identical functions, and I want to make Player a base class and Alien a derived class. The two classes are described below class Player(object): #Class attributes for class Player threshold = 50 n=0 #n is the number of players
6
2143
by: Frank Millman | last post by:
Hi all I have a question regarding inheritance. I have come up with a solution, but it is not very elegant - I am sure there is a more pythonic approach. Assume the following class definitions. class Table: def __init__(self,table_name,table_type): class Master(Table):
0
1303
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 situation. I have the following class structure: ASSEMBLY ATools
8
2998
by: Marco | last post by:
Hi all, I have a base class and some subclasses; I need to define an array of objects from these various subclasses. What I have is something like: { //I have a base class, something like: class CPeople {
4
1678
by: GiBo | last post by:
Hi all, I have a class URI and a bunch of derived sub-classes for example HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is module urllib & friends, however my actual problem however maps very well to this example). Now I want to pass a string to constructor of URI() and get an instance of one of the subclasses back. For example uri=URI('http://abcd/...') will make 'uri' an instance of HttpURI class, not instance of...
5
3154
by: ryanoasis | last post by:
Working on a C++ assignment and I cant figure out the problems I am having w/ Templates and Subclasses. I know there are issues with templates and certain compilers so I am not sure what the problem is exactly. I am hoping its an easy overlook. This class is of the linkedLIst, Iterator, and Node modified to use Templates and so that Iterator and Node are subclasses of List
5
2221
by: grossespinne | last post by:
Hi everybody! I have been thinking over the following problem: there are three classes: PageBase, which is the base class, PageA and PageB which are the subclasses of PageBase. In the index.php file I have a variable which I like to hold either an instance of PageA or PageB depending on the query string that is passed to index.php (e.g: if I get the query index.php?content=a, I need an instance of PageA, but if I get the query: index.php?...
10
2270
by: Karlo Lozovina | last post by:
Hi, what's the best way to keep track of user-made subclasses, and instances of those subclasses? I just need a pointer in a right direction... thanks. -- Karlo Lozovina -- Mosor
0
8370
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
8283
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8590
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
7302
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...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5620
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4147
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...
2
1591
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.