473,795 Members | 3,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Keeping track of subclasses and instances?

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
Oct 11 '07 #1
10 2283
Karlo Lozovina wrote:
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.
I'm not completely sure I understand the question but here goes. Instances of
classes are classes can be stored in lists or dictionaries. In lists you
reference them via their index (or iterate over them) and in dictionaries you
can give them a name that is used as a key.

Hope this helps.

-Larry
Oct 11 '07 #2
Larry Bates wrote:
I'm not completely sure I understand the question but here goes.
Instances of
classes are classes can be stored in lists or dictionaries. In lists you
reference them via their index (or iterate over them) and in dictionaries
you can give them a name that is used as a key.
I wish if it were that simple :).

Here is a longer description - I have a function that given input creates a
custom class and returns it back. The user is free to subclass that (even
more, he should do that), and of course he will make instances of those
subclasses. Now, my question is how to keep track of subclasses and their
instances, without the need for user interaction (appending them to a list,
or adding to dictionary)?

Thanks,

--
Karlo Lozovina - Mosor
Oct 11 '07 #3
On Oct 10, 9:19 pm, Karlo Lozovina <_kar...@mosor. netwrote:
Larry Bates wrote:
I'm not completely sure I understand the question but here goes.
Instances of
classes are classes can be stored in lists or dictionaries. In lists you
reference them via their index (or iterate over them) and in dictionaries
you can give them a name that is used as a key.

I wish if it were that simple :).

Here is a longer description - I have a function that given input creates a
custom class and returns it back. The user is free to subclass that (even
more, he should do that), and of course he will make instances of those
subclasses. Now, my question is how to keep track of subclasses and their
instances, without the need for user interaction (appending them to a list,
or adding to dictionary)?

Thanks,

--
Karlo Lozovina - Mosor

I guess Larry's actual question was why do *you* need to keep track of
users' instances and subclasses and don't let them keep track on their
own if/when they need it. I realize there are legitimate use cases for
this but it's not typical. Anyway, here's something to get you
started; all a user has to do is derive (directly or indirectly) from
InstanceTracker and, if a class C defines __init__,
super(C,self)._ _init__() should be called explicitly:
from collections import deque
from weakref import WeakKeyDictiona ry

class InstanceTracker (object):
def __init__(self):
try: all = self.__class__. __dict__['__instances__']
except KeyError:
self.__class__. __instances__ = all = WeakKeyDictiona ry()
all[self] = None

def iter_instances( cls):
return iter(cls.__dict __.get('__insta nces__',[]))

def iter_descendant _classes(cls):
memo = set()
unvisited = deque(cls.__sub classes__())
while unvisited:
top = unvisited.pople ft()
if top not in memo:
memo.add(top); yield top
unvisited.exten d(top.__subclas ses__())

#----- example --------------------------------------
if __name__ == '__main__':

class A(InstanceTrack er): pass
class B1(A): pass
class B2(A): pass
class C1(B1,B2):
def __init__(self):
super(C1,self). __init__()
class C2(B1,B2): pass
class D(C1,C2): pass

items = [A(),B1(),B2(),C 1(),C1(),D(),A( ),B2()]
print ' * Instances per class'
for c in iter_descendant _classes(A):
print c, list(iter_insta nces(c))

print ' * Instances per class (after delete)'
del items
for c in iter_descendant _classes(A):
print c, list(iter_insta nces(c))
HTH,
George

Oct 11 '07 #4
On Thu, 11 Oct 2007 03:19:07 +0200, Karlo Lozovina wrote:
Here is a longer description - I have a function that given input
creates a custom class and returns it back. The user is free to subclass
that (even more, he should do that), and of course he will make
instances of those subclasses. Now, my question is how to keep track of
subclasses and their instances, without the need for user interaction
(appending them to a list, or adding to dictionary)?
The real question is why you think you need to keep track of them instead
of letting the user and/or Python keep track of them, like any other
object.
--
Steven.
Oct 11 '07 #5
On Oct 10, 8:17 pm, Karlo Lozovina <_kar...@mosor. netwrote:
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
This recipe does what you want, with the intent of providing
automatic finalization of the instances, but you should be able
to tweak it to do everything you wish:

http://aspn.activestate.com/ASPN/Coo.../Recipe/523007

Michele Simionato

Oct 11 '07 #6
On Wed, 10 Oct 2007 21:35:44 -0700, Michele Simionato wrote:
On Oct 10, 8:17 pm, Karlo Lozovina <_kar...@mosor. netwrote:
>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

This recipe does what you want, with the intent of providing automatic
finalization of the instances, but you should be able to tweak it to do
everything you wish:

http://aspn.activestate.com/ASPN/Coo.../Recipe/523007

Well, that answers my earlier question about why you might want to track
instances. But it seems like an unnecessarily complicated way of doing it.

From your recipe:

[module deallocating.py]

import logging

class C(object):
def __init__(self):
logging.warn('A llocating resource ...')
def __del__(self):
logging.warn('D e-allocating resource ...')
print 'THIS IS NEVER REACHED!'

if __name__ == '__main__':
c = C()
Is there a problem with writing C like this?

class C(object):
def __init__(self):
logging.warn('A llocating resource ...')
self.__log = logging.warn
def __del__(self):
self.__log('De-allocating resource ...')
print 'THIS IS REACHED!'

It works for me. Have I missed something?
--
Steven.
Oct 11 '07 #7
Karlo Lozovina schrieb:
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.
New style classes have a __subclasses__ class method that shows the direct subclasses:

Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright" , "credits" or "license" for more information.
>>object.__subc lasses__()
[<type 'type'>, <type 'weakref'>, <type 'int'>, <type 'basestring'>, <type 'list'>, <type 'NoneType'>, ...
>>>
No builtin mechanism for instances exists, afaik.

Thomas

Oct 11 '07 #8
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites:
Is there a problem with writing C like this?
class C(object):
def __init__(self):
logging.warn('A llocating resource ...')
self.__log = logging.warn
It works for me. Have I missed something?
I thought the OP wanted to the program to notice when subclasses were
created, not just instances of them. As Andreas Kraemer described,
you can do that with a metaclass.
Oct 11 '07 #9
On Oct 11, 7:16 am, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com .auwrote:
Is there a problem with writing C like this?

class C(object):
def __init__(self):
logging.warn('A llocating resource ...')
self.__log = logging.warn
def __del__(self):
self.__log('De-allocating resource ...')
print 'THIS IS REACHED!'

It works for me. Have I missed something?
Another more common workaround is to use default arguments:

class C(object):
def __init__(self):
logging.warn('A llocating resource ...')
def __del__(self, warn=logging.wa rn):
warn('De-allocating resource ...')
print 'THIS IS REACHED!'

But, as you know, I want to remove __del__ because of the problem with
reference
cycles, not because of this little issue with the cleanup mechanism
(which BTW is shared
also by the weak references callback mechanism).

Michele Simionato

Oct 11 '07 #10

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

Similar topics

8
3006
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 {
3
1711
by: Gregory Bond | last post by:
I'm building a class hierarchy that needs to keep as a class variable a reference to a (non-member) function, so that different subclasses can use different generator functions. But it seems Python is treating the function as a member function because the reference to it is in class scope.... Here's a simple case of what I'm trying (in the real code, fn is a function that returns a database connection relevant to that subclass): >...
2
3093
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing this by aggregating new content from all databases into a single indexed database and then saving a timestamp in the account database (for the current user) that tells me when the user last read items in the aggregated database.
1
1911
by: Joshua Russell | last post by:
I'm writing some software that opens multiple instances of a single class in new threads. I need a way of keeping track of all these class instances in some kind of collection. I'm basicaly writing an MSN Messenger like application. The threads being, in this case, the chat windows. I would like to be able to access the various referances in a similar way to the following if it can be done... convoThreads.someFunctionInTheClass(); Has...
9
5493
by: Alfred Taylor | last post by:
I'm testing the waters of n-tier development and I ran into a scenario that I'm not sure what the best solution would be. I have a Company object which contains a collection of contacts retrieved from a database. In the presentation layer, the user will be able to add/delete/modify this collection in which case it needs to be synced with the database. The question is basically how best to do this? Aside from overriding the add/remove...
2
2768
by: metaperl | last post by:
I'm actually taking Microsoft's 2779 and just finished a lab where we kept track of our changes to the database. However, I'm not happy with the scripts interface because it does not tell me the chronological order of my changes to the database. Could someone share with me their technique for keeping track of database changes? I'm actually thinking a set of tables would be best, because sometimes
7
2080
by: Daniel Nogradi | last post by:
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
2
3396
by: De_Cisse | last post by:
Hi all, I'm working on an application in which I already make some preparations to be able to work in a frontend and backend database, even if this isn't the issue a this moment. I'm using VBA classes for this (I know not the easiest way, but I have made some considerations and I want to to it this way as VBA classes are some new stuff to explore for me). In a class 'client' I get the data from the database and put it in
0
1102
by: Klaus Jensen | last post by:
Hi In a repeater-control, in the <SeparatorTemplatei have placed a webusercontrol, I have made. That works great- However, I want to know be able to only display this WebUserControl a certain number of times. Basicly I need the WebUserControl itself to know, how many other instances of the webusercontrol was displayed on the page, when I run it.
0
9519
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,...
0
10437
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
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
9042
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
7538
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
6780
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
5437
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
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.