473,657 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

finding the parent class (not superclass) of the currently executingmethod derived from a Borg class

I want to create a class derived from a Borg class that can
instantiated as part of a script or be contained in other classes.
When methods from the Borg class are called, I would like to know the
name of the class that contains the Borg class.

I've played a bit with inspect and _getframe from the sys module but
get inconsistent results. The main problem is if the Borg class is
instantiated outside a containing class, then I need to go up a
different number of stack frames. But this information isn't
available till after I've run out of stack frames.

Hopefully the following code better describes what I'm looking to do.

import sys

class Borg:
_shared_state = {}
def __init__(self):
self.__dict__=s elf._shared_sta te

class Assimilated(Bor g):
valueByCaller = {}

def __init__(self, setupvalue):
print "In Assimilated.__i nit__()"
print "setupvalue is: " + str(setupvalue)

# would like key to be name of class (or module) that
# contins Assimilated
callerID = sys._getframe(1 ).f_code.co_nam e

self.valueByCal ler[callerID] = setupvalue

print self.valueByCal ler

def action(self, calledvalue):
print "In Assimilated.act ion()"
print "self.__classna me__: " + self.__class__. __name__
print "calledvalu e is: " + str(calledvalue )

print "self.valueByCa ller"
print self.valueByCal ler

# need to get proper key depending on which class (or module)
# made the call
# print "0: " + sys._getframe(0 ).f_code.co_nam e
# print "1: " + sys._getframe(1 ).f_code.co_nam e
# print "2: " + sys._getframe(2 ).f_code.co_nam e
# print "3: " + sys._getframe(3 ).f_code.co_nam e
callerID = sys._getframe(2 ).f_code.co_nam e
print "callerID"
print callerID

if(self.valueBy Caller[callerID] <= calledvalue):
print "doing the action"
class A:
assim_object = Assimilated(2)

def __init__(self):
self.assim_obje ct.action(2)
self.assim_obje ct.action(3)

class B:
assim_object = Assimilated(3)

def __init__(self):
self.assim_obje ct.action(3)
self.assim_obje ct.action(4)

class C:
assim_object = Assimilated(4)

def __init__(self):
self.assim_obje ct.action(4)
self.assim_obje ct.action(5)
a=A()
b=B()
c=C()

obj=Assimilated (3)
#obj.action(3)
When I run this, I get the following output:

In Assimilated.__i nit__()
setupvalue is: 2
{'A': 2}
In Assimilated.__i nit__()
setupvalue is: 3
{'A': 2, 'B': 3}
In Assimilated.__i nit__()
setupvalue is: 4
{'A': 2, 'C': 4, 'B': 3}
In Assimilated.act ion()
self.__classnam e__: Assimilated
calledvalue is: 2
self.valueByCal ler
{'A': 2, 'C': 4, 'B': 3}
callerID
<module>
Traceback (most recent call last):
File "\CallerID. py", line 67, in <module>
a=A()
File "\CallerID. py", line 49, in __init__
self.assim_obje ct.action(2)
File "\CallerID. py", line 41, in action
if(self.valueBy Caller[callerID] <= calledvalue):
KeyError: '<module>'

What I found most peculiar when I started this was that the
valueByCaller dictionary was completely populated before the __init__
method of a was executed. I'm pretty sure that this has to do with
the difference between when the object gets instanced and when it gets
initialized, but I need to do some more research and reading to be
able to explain it to myself.

Thanks for any help you can give me.

Kevin
Sep 8 '08 #1
1 1098
seanacais a écrit :
I want to create a class derived from a Borg class that can
instantiated as part of a script or be contained in other classes.
When methods from the Borg class are called, I would like to know the
name of the class that contains the Borg class.
I've played a bit with inspect and _getframe from the sys module but
get inconsistent results. The main problem is if the Borg class is
instantiated outside a containing class, then I need to go up a
different number of stack frames. But this information isn't
available till after I've run out of stack frames.
The simplest solution is usually the better : explicitely pass the
caller (whether instance or module or whatever you want)

Hopefully the following code better describes what I'm looking to do.

import sys

class Borg:
_shared_state = {}
def __init__(self):
self.__dict__=s elf._shared_sta te

class Assimilated(Bor g):
valueByCaller = {}
You understand that, being a class attribute, valueByCaller won't be
part of the Borg's _shared_state ?
def __init__(self, setupvalue):
print "In Assimilated.__i nit__()"
print "setupvalue is: " + str(setupvalue)

# would like key to be name of class (or module) that
# contins Assimilated
callerID = sys._getframe(1 ).f_code.co_nam e

self.valueByCal ler[callerID] = setupvalue

print self.valueByCal ler
Anyway, since you override __init__ and don't call Borg.__init__, your
Assimilated class doesn't behave as a Borg.

(snip)

>
When I run this, I get the following output:

In Assimilated.__i nit__()
setupvalue is: 2
{'A': 2}
In Assimilated.__i nit__()
setupvalue is: 3
{'A': 2, 'B': 3}
In Assimilated.__i nit__()
setupvalue is: 4
{'A': 2, 'C': 4, 'B': 3}
(snip)
>
What I found most peculiar when I started this was that the
valueByCaller dictionary was completely populated before the __init__
method of a was executed.
Indeed. In classes A, B and C, assim_object is class attribute - so it
is instanciated when the class statement is executed.
I'm pretty sure that this has to do with
the difference between when the object gets instanced and when it gets
initialized,
Not at all. It has to do with the fact that all statements within a
class block are executed before the class statement itself is executed.
And since your class statements are at the top-level, they are executed
when the module is initialised (that is, passed to the python runtime or
first imported).
but I need to do some more research and reading to be
able to explain it to myself.
Indeed. May I suggest that you *learn* Python's object model and
Python's execution model instead of assuming anything ? This will save
you a whole lot of time and frustration !-)
Sep 9 '08 #2

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

Similar topics

5
3645
by: Suzanne Vogel | last post by:
Hi, Given: I have a class with protected or private data members, some of them without accessor methods. It's someone else's class, so I can't change it. (eg, I can't add accessor methods to the parent class, and I can't make some "helper" class a friend of the parent class to help in accessing the data.) Problem: I want to derive a class that has a copy constructor that properly copies those data members.
16
2667
by: Suzanne Vogel | last post by:
Hi, I've been trying to write a function to test whether one class is derived from another class. I am given only id's of the two classes. Therefore, direct use of template methods is not an option. Let's call the id of a class "cid" (for "class id"). The function signature should look like this: ******************************************
9
5117
by: Martin Herbert Dietze | last post by:
Hello, I would like to implement a callback mechanism in which a child class registers some methods with particular signatures which would then be called in a parent class method. In half-code this should in the end look like this: In the child class:
9
2063
by: Ken Varn | last post by:
Is there anyway to override a public virtual method or property so that it is private in my derived class? I tried using new on the property and making it private, but no luck. -- ----------------------------------- Ken Varn Senior Software Engineer Diebold Inc.
11
2866
by: Darren.Ratcliffe | last post by:
Hi guys Posted what was probably a rather confusing post about this the other day, so I am going to have another go and see if I can make more sense. This sis purely a I've got a base class called animal, and from within animal you can access lots more classes such as feline, canine, reptile and amphibian.....
7
13674
by: S. Lorétan | last post by:
Hi guys, Sorry for this stupid question, but I don't know why it isn't working. Here is my (example) code: namespace Test { class A { public string Label1; }
3
2959
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single
6
14868
by: howa | last post by:
Consider example: Animal = function(age) { this.age = age; }; Animal.prototype.sleep = function() { alert("Animal Sleeping..."); };
12
6113
by: Gordon | last post by:
I want to provide a set of static functions in a superclass that work with class constants defined in a decendant of that class. Unfortunately I've run into a snag with this idea. Example: class SuperClass { const CNST = 'Super class'; public static function getCnst () {
0
8312
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
8732
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...
1
8504
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
7337
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
6169
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
5632
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
4159
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...
1
2732
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
1622
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.