473,586 Members | 2,495 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help needed with classes/inheritance

Hello everybody,

I am building a code for surface meshes (triangulations for instance).
I need to implement Body objects (bodies can be points, segments,
triangles and so on), then a Mesh will be a collection of bodies,
together with their neighbourhood relations.
I also need OrientedBody objects, which consist in a body
together with a plus or minus sign to describe its orientation.
So, basically an OrientedBody is just a Body with an
integer label stuck on it.

I implemented it in a very crude manner:
------------------------------------------
class Body:
[...]
class OrientedBody:
def __init__ (self,b,orient= 1):
# b is an already existing body
assert isinstance(b,Bo dy)
self.base = b
self.orientatio n = orient
-------------------------------------------

My question is: can it be done using inheritance ?
I recall that I need three distinct objects:
the basic (non-oriented) body, the same body with positive
orientation and the same body with negative orientation.

Thank you. Cristian Barbarosie
http://cmaf.fc.ul.pt/~barbaros
Jun 27 '08 #1
7 1769
barbaros a écrit :
Hello everybody,

I am building a code for surface meshes (triangulations for instance).
I need to implement Body objects (bodies can be points, segments,
triangles and so on), then a Mesh will be a collection of bodies,
together with their neighbourhood relations.
I also need OrientedBody objects, which consist in a body
together with a plus or minus sign to describe its orientation.
So, basically an OrientedBody is just a Body with an
integer label stuck on it.

I implemented it in a very crude manner:
------------------------------------------
class Body:
Unless you need compatibility with pre-2.2 Python versions, use a
new-style class instead:

class Body(object):
[...]
class OrientedBody:
def __init__ (self,b,orient= 1):
# b is an already existing body
assert isinstance(b,Bo dy)
self.base = b
self.orientatio n = orient
-------------------------------------------

My question is: can it be done using inheritance ?
Technically, yes:

class OrientedBody(Bo dy):
def __init__(self, orient=1):
Body.__init__(s elf)
self.orient = 1

Now if it's the right thing to do is another question... Another
possible design could be to have an orient attribute on the Body class
itself, with 0 =non-oriented (default), 1 ='plus', -1 ='minus' (or
any other convention, depending on how you use this attribute).

Jun 27 '08 #2
barbaros wrote:
Hello everybody,

I am building a code for surface meshes (triangulations for instance).
I need to implement Body objects (bodies can be points, segments,
triangles and so on), then a Mesh will be a collection of bodies,
together with their neighbourhood relations.
I also need OrientedBody objects, which consist in a body
together with a plus or minus sign to describe its orientation.
So, basically an OrientedBody is just a Body with an
integer label stuck on it.

I implemented it in a very crude manner:
------------------------------------------
class Body:
[...]
class OrientedBody:
def __init__ (self,b,orient= 1):
# b is an already existing body
assert isinstance(b,Bo dy)
self.base = b
self.orientatio n = orient
-------------------------------------------
class Body(object) :
...

class OrientedBody (Body):
def __init__(self, orientation = 1) :
Body.__init__(s elf)
self.orientatio n = orientation

as noted
But, also.

as a rule of thumb .. if you are using "isinstance " in a class to
determine what class a parameter is ... you have broken the OO contract.
Remember, every class ought to have a well defined internal state and
a well defined interface to its state.

If I write --

class foo (object):
def __init__ :
pass

def some_func (self, val) :
if isinstance (val, "bar") :
....

Then I am either doing something very wrong or very clever (either can
get me in trouble)

In Python it is preferred that I write two functions some_func_a and
some_func_b

e.g.

def some_func_a (self, val = None, class = bar) :
assert(isinstan ce (class, "bar"), True)
....

def some_func_b (self, val = None, class = baz) :
assert (isinstance (class, "baz"), True)

C++ and Java try to enforce the OO contract by making data and methods
private, protected or public. Which helps -- but leads to some
confusion (what is protected inheritance in C++????) Python exposes all
of its classes internals to everyone -- but that doesn't mean you should
touch them!!

As Larry Wall once wrote, "There is a difference between, 'do not enter
my living room because I asked you not to' and 'do not enter my living
room because I have a shotgun'"

Python adopts the 'do not touch my private parts because I asked you not
to' idiom. (In C++, only friends can touch your privates ... ;-)

So -- be mindful that checking the class of well defined parameters at
anytime is breaking the contract -- you may need to do it -- but it is
more likely that you aren't adhering to good OOD.

Does that make any sense?

Seriously -- I have not had any coffee yet and I am still new at Python.
-- Andrew

>
My question is: can it be done using inheritance ?
I recall that I need three distinct objects:
the basic (non-oriented) body, the same body with positive
orientation and the same body with negative orientation.

Thank you. Cristian Barbarosie
http://cmaf.fc.ul.pt/~barbaros
Jun 27 '08 #3
Andrew Lee a écrit :
(snip)
as a rule of thumb .. if you are using "isinstance " in a class to
determine what class a parameter is ... you have broken the OO contract.
Nope.
Remember, every class ought to have a well defined internal state and a
well defined interface to its state.
I don't see how the part about the internal state relates to the problem
here.

If I write --

class foo (object):
def __init__ :
pass

def some_func (self, val) :
if isinstance (val, "bar") :
....

Then I am either doing something very wrong
If you do so in a desperate attempt to emulate static typing in Python,
then yes, you're doing something very wrong. Else:
or very clever
Not necessarily. Given Python's dynamic typing, there's no builtin
OneObviousWay(t m) way to dispatch on different functions based on
argument's type - something often done in statically typed OOPLs using
method overridding (ie: different methods with same name but different
signatures). Doing a manual dispatch based on argument's type, while not
good OO style, is sometimes the simplest working solution, and a good
enough one for the problem at hand. Having different methods for
different arg types has the drawback that you don't have one single
generic function/method that you can use as a callback.

Having a real multidispatch (or rule-based dispatch etc) system either
builtin or in the stdlib would indeed be much cleaner. Until then, there
are a couple third-part packages solving this problem, but it can be
overkill for simple problems (and add unneeded/unwanted dependencies).

my 2 cents.
Jun 27 '08 #4
On Apr 23, 10:48 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@websiteburo.i nvalidwrote:
>
My question is: can it be done using inheritance ?

Technically, yes:

class OrientedBody(Bo dy):
def __init__(self, orient=1):
Body.__init__(s elf)
self.orient = 1

Now if it's the right thing to do is another question...
If I understand correctly, in the above implementation I cannot
define firstly a (non-oriented) body, and then build, on top of it,
two bodies with opposite orientations. The point is, I want
both oriented bodies to share the same base Body object.
Another
possible design could be to have an orient attribute on the Body class
itself, with 0 =non-oriented (default), 1 ='plus', -1 ='minus' (or
any other convention, depending on how you use this attribute).
The above comments apply here, too.

In what concerns other suggestion, about Python language,
I shall do my best to understand them and apply them.

Thank you. Cristian Barbarosie
http://cmaf.fc.ul.pt/~barbaros
Jun 27 '08 #5
On Apr 23, 10:44*am, barbaros <barba...@ptmat .fc.ul.ptwrote:
>
If I understand correctly, in the above implementation I cannot
define firstly a (non-oriented) body, and then build, on top of it,
two bodies with opposite orientations. The point is, I want
both oriented bodies to share the same base Body object.
What you are describing is composition+del egation, not inheritance,
and it would be the same answer in Java, C++, or OO-langue-du-jour.
Python makes delegation to the contained object easier than the others
(except maybe for OOldj) - no need to implement all the methods of the
contained object in the container, that just delegate the call to the
contained; use __getattr__ to get attributes of the contained object
that are not defined on the container (methods are attributes, too) as
shown below. No inheritance in this example at all.

-- Paul
class BodyWithoutOrie ntation(object) :
def __init__(self,c olor):
self.color = color
def show_orientatio n(self):
print "I don't lean one way or the other"

class OrientedBody(ob ject):
def __init__(self,b ase,orientation ):
self.base_body = base
self.orientatio n = orientation
def show_orientatio n(self):
print "I lean to the " + \
{
OrientedBody.RI GHT : "right",
OrientedBody.LE FT : "left",
}[self.orientatio n],
print "and my color is " + self.color
# delegate any other attr lookups to the base_body object
def __getattr__(sel f,attr):
return getattr(self.ba se_body,attr)
OrientedBody.RI GHT = object()
OrientedBody.LE FT = object()

class LeftRightBody(o bject):
def __init__(self,b ):
self.common_bas e = b
self.left = OrientedBody(b, OrientedBody.LE FT)
self.right = OrientedBody(b, OrientedBody.RI GHT)
def show_orientatio n(self):
print "I do both of these:"
print "- ",
self.left.show_ orientation()
print "- ",
self.right.show _orientation()

base = BodyWithoutOrie ntation("purple ")
lr = LeftRightBody(b ase)

base.show_orien tation()
lr.show_orienta tion()

Prints:
I don't lean one way or the other
I do both of these:
- I lean to the left and my color is purple
- I lean to the right and my color is purple
Jun 27 '08 #6
barbaros a écrit :
On Apr 23, 10:48 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@websiteburo.i nvalidwrote:
>>My question is: can it be done using inheritance ?
Technically, yes:

class OrientedBody(Bo dy):
def __init__(self, orient=1):
Body.__init__(s elf)
self.orient = 1

Now if it's the right thing to do is another question...

If I understand correctly, in the above implementation I cannot
define firstly a (non-oriented) body, and then build, on top of it,
two bodies with opposite orientations. The point is, I want
both oriented bodies to share the same base Body object.
Then it's not a job for inheritence, but for composition/delegation -
Sorry but I didn't get your specs quite right :-/

Now the good news is that Python makes composition/delegation close to
a no-brainer:

class Body(object):
# definitions here

class OrientedBody(ob ject):
# notice that we *dont* inherit from Body
def __init__(self, body, orient):
self._body = body
self.orient = orient

def __getattr__(sel f, name):
try:
return getattr(self._b ody, name)
except AttributeError:
raise AttributeError(
"OrientedBo dy object has no attribute %s" % name
)
def __setattr__(sel f, name, val):
# this one is a bit more tricky, since you have
# to know which names are (or should be) bound to
# which object. I use a Q&D approach here - which will break
# on computed attributes (properties etc) in the Body class -
# but you can also define a class attribute in either Body
# or OrientedBody to explicitly declare what name goes where
if name in self._body.__di ct__:
setattr(self._b ody, name, val)
else:
object.__setatt r__(self, name, value)

Jun 27 '08 #7
Thanks to Paul McGuire and Bruno Desthuilliers for their comprehensive
answers. This is exactly what I was looking for, except I did not know
the correct name (composition/delegation). Now all I have to do is to
study the supplied code, understand it and adapt it to my problem.

Thank you very much. Cristian Barbarosie
http://cmaf.ptmat.fc.ul.pt/~barbaros
Jun 27 '08 #8

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

Similar topics

5
2110
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
4
3129
by: Jeff T. | last post by:
Hello, I have an existing set of C# classes that encapsulate our application data. They are in a heirachy with each subclass defining more specific types of data. I would like to serialize these data objects as XML but perserve the relationships in the XML document. For example, if my classes were: public class GenericItem { }
4
1461
by: vivekian | last post by:
Hi, Have this following hierarchy which am implementing for a networking program. The base class 'ASocket' is the base class from which 'AListener' and 'ATalker' inherit . None of the functions in the derived classes would override functions from the base class. The derived classes would extend the base class. A couple of doubts : 1....
13
3233
by: Fao | last post by:
Hello, I am having some problems with inheritance. The compiler does not not return any error messages, but when I execute the program, it only allows me to enter the number, but nothing else happend. I think the problem may be in my input function or in the main function. If anyone out there can help me it woul be greatly appreciated. ...
9
1704
by: Chrissy | last post by:
I took a C# class as an elective and received an incomplete in it and am desparate for help. I have two assignments left (arrays and inheritance) and would gladly pay anyone that can assist me with this. I want you to know that I'm a 41 year old mother of three boys (ages 9, 7, and 2) and have done my very best to muddle through this...
0
7915
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...
0
7841
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...
0
8204
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. ...
0
8220
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...
1
5712
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...
0
5392
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...
0
3838
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...
0
3869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
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

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.