473,779 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

need help on sublcass and scope

I'm an OOP newbie, and needs help on subclassing from different module.

I made a base module a.py which contains two classes C1 and C2;

## start of a.py

class C1(object):
def m(self):
print "method m in class C1 in module a"

class C2(object):
def __init__(self):
print "class C2 in module a"
self.a = C1()
self.a.m()

## end of of a.py

Then, I made another module b.py which extends this base module;

## start of b.py

import a

class C1(a.C1):
def m(self):
print "method m in class C1 in module b"
a.C1.m(self)

class C2(a.C2):
def __init__(self):
print "class C2 in module b"
a.C2.__init__(s elf)

## end of of b.py

When I instantiate C2, I get;
import b
i = b.C2() class C2 in module b
class C2 in module a
method m in class C1 in module a
It doesn't use class C1 in module 'b', but uses C1 in module 'a' because
the last line in b.py 'a.c2.__init__( self)' runs with module scope a.
So I tweaked the C1 instantiation line in a.py from

self.a = C1()

to

import sys
self.a = sys.modules[self.__module__].C1()

and got the result I expected;
import b
i = b.C2() class C2 in module b
class C2 in module a
method m in class C1 in module b
method m in class C1 in module a


but it looks like an ugly hack to me.
If there's common OOP idiom to handle this kind of problem, give me
some pointer.

Thanks,
Inyeol

Jul 18 '05 #1
1 1329
Inyeol Lee wrote:
I'm an OOP newbie, and needs help on subclassing from different module.

I made a base module a.py which contains two classes C1 and C2;
[...]
but it looks like an ugly hack to me.
If there's common OOP idiom to handle this kind of problem, give me
some pointer.


I think with all these a, b and Cs, you raised the abstraction level too
high. To me - at least - it remains unclear what you are trying to achieve.

I've made a bold guess and tweaked your example to output what you expected
without having to mess with sys.modules.

#a.py
class C1(object):
def m(self):
print "method m in class C1 in module a"

class C2(object):
def __init__(self, a=None):
print "class C2 in module a"
if a is None: a = C1()
self.a = a
self.a.m()
#b.py
import a

class C1(a.C1):
def m(self):
print "method m in class C1 in module b"
a.C1.m(self)

class C2(a.C2):
def __init__(self):
print "class C2 in module b"
a.C2.__init__(s elf, C1())

If you want to modify a part of the C2 implementation independently of the
C2 hierarchy, you could make C1 a Mixin:

#a.py vs 2
class C1(object):
def m(self):
print "method m in class C1 in module a"

class C2(object):
def __init__(self, a=None):
print "class C2 in module a"
self.m()

#b.py vs 2
import a
class C1(a.C1):
def m(self):
print "method m in class C1 in module b"
super(C1, self).m()

class C2(a.C2, C1):
def __init__(self):
print "class C2 in module b"
super(C2, self).__init__( )

The beauty of this approach becomes visible if you add further subclasses to
C1:

#c.py aka b.py vs 3
import a
class C11(a.C1):
def m(self):
print "method m in class C11 in module c"
super(C11, self).m()

class C12(a.C1):
def m(self):
print "method m in class C12 in module c"
super(C12, self).m()

class C2(a.C2, C11, C12):
def __init__(self):
print "class C2 in module b"
super(C2, self).__init__( )

a.C1 occurs twice in the hierarchy, so how often would you expect
"method m in class C1 in module a" to be printed?
I you anser 1, then which of the following messages will be omitted:
"method m in class C11 in module c" or "method m in class C12 in module c"

Let's try:
import c
c.C2() class C2 in module b
class C2 in module a
method m in class C11 in module c
method m in class C12 in module c
method m in class C1 in module a
<c.C2 object at 0x40295f0c>


Every m() was exactly called once!

However, I'm not an OOP newbie and still have doubts if I've got the above
right, so I would recommend the first approach. After all, Python is more
about readability and ease of use than clever tricks to confuse the
uninitiated.
Peter

PS: For more information, google for python and descrintro.

Jul 18 '05 #2

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

Similar topics

7
2310
by: Ben Thomas | last post by:
Hi all, I'm having some trouble understanding the behavior of std::ostringstream. (I'm using Visual Studio .Net & STL port 4.5.3). I'll appreciate if someone can give me a little explanation of this behavior and how it is possible... Here's my code ////////////////////////// #include <stdio.h>
3
2237
by: Mr. Clean | last post by:
Very new to XML style sheets and need some help getting this XML: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE CDSLogger SYSTEM "CDSLogger.dtd"> <CDSLogger> <ErrorObject> <BatchName>This is the first batch</BatchName> <ErrorCode>12904</ErrorCode> <Success>True</Success> </ErrorObject>
15
3681
by: drdoubt | last post by:
using namespace std In my C++ program, even after applying , I need to use the std namespace with the scope resolution operator, like, std::cout, std::vector. This I found a little bit cumbersome to always include std. I somewhere found a trick to overcome this problem. By using using std::cout;
1
6092
by: bin_P19 P | last post by:
the code i have got is as follows and now im stuck <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Shopping Cart</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link rel="StyleSheet" href="css/style.css" type="text/css">
106
6476
by: xtra | last post by:
Hi Folk I have about 1000 procedures in my project. Many, many of them are along the lines of function myfuntion () as boolean on error goto er '- Dim Dbs as dao.database Dim Rst as dao.recordset
5
2095
by: pembed2003 | last post by:
Hi all, I am reading the book "C How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope function-prototype scope I think(might be wrong):
8
3378
by: TTroy | last post by:
I have a few questions about "scope" and "visibility," which seem like two different things. To me "visibility" of the name of a function or object is the actual code that can use it in an actual program. To me "scope" of the name of a function or object are the general rules for the areas of a program that can through a declaration, have "visibility."
2
9199
by: Jon Davis | last post by:
The garbage handler in the .NET framework is handy. When objects fall out of scope, they are automatically destroyed, and the programmer doesn't have to worry about deallocating the memory space for those objects. In fact, all the programmer has to worry about is the total sum of objects loaded into RAM at any known point. Memory leaks are not a problem. .... So one would like to think. The reality is that delegates and event...
3
4751
sammyboy78
by: sammyboy78 | last post by:
I'm trying to display an array of objects using a GUI. My instructions are that the CD class and it's sublcass don't need to change I just need to modify class CDInventory to include the GUI. I'm not even sure if the way I've written this is going to work but anyway, I keep getting a compilation error that says: C:\Documents and Settings\Sam\GUICDInventory.java:22: cannot find symbol symbol : constructor JList(CDInventory) location: class...
0
9632
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
9471
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
10136
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
10071
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
9925
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
8958
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
6723
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
5372
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
3631
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.