473,324 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

refering to base classes

hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

thanks
glenn

Aug 29 '06 #1
21 1735
glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

thanks
glenn
Try this:

class dog(creature):
.....
def voice(self):
print "brace your self:"
creature.voice(self)

This should do it.
Aug 29 '06 #2
Chaz Ginger wrote:
glenn wrote:
>hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

thanks
glenn
Try this:

class dog(creature):
.....
def voice(self):
print "brace your self:"
creature.voice(self)

This should do it.
I did forget to mention that in 'dog"s' __init__ you had better call
creature's __init__. You might make it look like this:

def __init__(self):
self.noise = 'bark'
creature.__init__(self)

There is another approach - using Superclass - but I will leave that
exercise to the reader.

Aug 29 '06 #3
glenn wrote:
[...] In this trivial example, how could I modify the voice method of
'dog' to call the base class 'creatures' voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"
If you want dog.voice() to just print "voice: bark", you just have to omit
the voice method for the dog class: it will be inherited from creature.

If you want dog.voice() to do something else, you can call superclass'
method like this:

def voice(self):
creature.voice(self)
print "brace your self"
any_other_magic()

HTH
--
Roberto Bonvallet
Aug 29 '06 #4
glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

<ot>
It might be better to use newstyle classes if you can. Also, the
convention is to use CamelCase for classes names (unless you have a
strong reason to do otherwise).
</ot>

Here you could use a class attribute to provide a default:

class Creature(object):
noise = ""

def voice(self):
return "voice:" + self.noise
class Dog(Creature):
noise="bark"

def voice(self):
print "brace your self:"
return Creature.voice(self)
# can also use this instead, cf the Fine Manual
return super(Dog, self).voice()

My 2 cents
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 29 '06 #5
Chaz Ginger wrote:
Chaz Ginger wrote:
glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

I did forget to mention that in 'dog"s' __init__ you had better call
creature's __init__. You might make it look like this:

def __init__(self):
self.noise = 'bark'
creature.__init__(self)
There's a problem with Chaz's __init__() method. Notice that the
creature class's __init__ sets self.noise to the empty string. In this
case, the superclass's __init__() method should be called first:

class dog(creature):
def __init__(self):
creature.__init__(self)
self.noise = "bark"
def voice(self):
print "brace your self:"
creature.voice(self)

--Jason

Aug 29 '06 #6
Jason wrote:
Chaz Ginger wrote:
>Chaz Ginger wrote:
>>glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"
I did forget to mention that in 'dog"s' __init__ you had better call
creature's __init__. You might make it look like this:

def __init__(self):
self.noise = 'bark'
creature.__init__(self)

There's a problem with Chaz's __init__() method. Notice that the
creature class's __init__ sets self.noise to the empty string. In this
case, the superclass's __init__() method should be called first:

class dog(creature):
def __init__(self):
creature.__init__(self)
self.noise = "bark"
def voice(self):
print "brace your self:"
creature.voice(self)

--Jason
Very true....I was showing him in "spirit only"...lol.
Chaz.
Aug 29 '06 #7

Chaz Ginger wrote:
Chaz Ginger wrote:
glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"

thanks
glenn
Try this:

class dog(creature):
.....
def voice(self):
print "brace your self:"
creature.voice(self)

This should do it.
I did forget to mention that in 'dog"s' __init__ you had better call
creature's __init__. You might make it look like this:

def __init__(self):
self.noise = 'bark'
creature.__init__(self)

There is another approach - using Superclass - but I will leave that
exercise to the reader.
first tip worked - funny thing was I =thought= I done that, but clearly
not - so thanks was going mad.
Superclass?... ok will look into this
thanks for reply(s)
Glenn

Aug 30 '06 #8

Bruno Desthuilliers wrote:
glenn wrote:
hi - Im quite new to python, wondering if anyone can help me understand
something about inheritance here. In this trivial example, how could I
modify the voice method of 'dog' to call the base class 'creatures'
voice method from with in it?

class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

def voice(self):
print "brace your self:"


<ot>
It might be better to use newstyle classes if you can. Also, the
convention is to use CamelCase for classes names (unless you have a
strong reason to do otherwise).
</ot>

Here you could use a class attribute to provide a default:

class Creature(object):
noise = ""

def voice(self):
return "voice:" + self.noise
class Dog(Creature):
noise="bark"

def voice(self):
print "brace your self:"
return Creature.voice(self)
# can also use this instead, cf the Fine Manual
return super(Dog, self).voice()

My 2 cents
ohh - interesting. Thanks for the camelCase tip - dont have a good
reason to do otherwise, just bad habits.
so for your $.02 do you see this as being, umm, superior in anyway to
creature.voice()?

glenn

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #9
Hi Roberto
If you want dog.voice() to just print "voice: bark", you just have to omit
the voice method for the dog class: it will be inherited from creature.
I would have thought this would be correct, but in this case, plus in
others im playin with, I get this issue:
-----------------------
given animal.py is:
class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

then I get this outcome...
>>>import animal
beagle=animal.dog
beagle.voice()
Traceback (most recent call last):
File "<input>", line 1, in ?
TypeError: unbound method voice() must be called with dog instance as
first argument (got nothing instead)
>>>
------------------------
So I guess it wants something in position of self?

any idea what Im doing wrong? - this would be very handy as its a point
Im stymied on a couple of 'projects'
thanks
Glenn
If you want dog.voice() to do something else, you can call superclass'
method like this:

def voice(self):
creature.voice(self)
print "brace your self"
any_other_magic()
HTH
--
Roberto Bonvallet
Aug 30 '06 #10
"glenn" <gl***@tangelosoftware.netwrites:
Bruno Desthuilliers wrote:
It might be better to use newstyle classes if you can. Also, the
convention is to use CamelCase for classes names (unless you have
a strong reason to do otherwise).
Note that this style is more correctly called TitleCase, since the
first letter of *every* word is capitalised, like in a headline (or
title). "camel case" is different -- see below.
ohh - interesting. Thanks for the camelCase tip - dont have a good
reason to do otherwise, just bad habits.
The style called camelCase (all words run together, capitalise first
letter of every word except the first) is prevalent in Java, where it
denotes the name of an *instance*, in contrast to a *class* which is
named with TitleCase.

The camelCase style is less popular in the Python world, where (as per
PEP 8) instances are named with all lower case, either joinedwords or
separate_by_underscores.

--
\ "Crime is contagious ... if the government becomes a |
`\ lawbreaker, it breeds contempt for the law." -- Justice Louis |
_o__) Brandeis |
Ben Finney

Aug 30 '06 #11
glenn wrote:
Hi Roberto
>>If you want dog.voice() to just print "voice: bark", you just have to omit
the voice method for the dog class: it will be inherited from creature.

I would have thought this would be correct, but in this case, plus in
others im playin with, I get this issue:
-----------------------
given animal.py is:
class creature:
def __init__(self):
self.noise=""
def voice(self):
return "voice:" + self.noise

class dog(creature):
def __init__(self):
self.noise="bark"

then I get this outcome...
>>>>import animal
beagle=animal.dog
[...]

Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 30 '06 #12
Ben Finney wrote:
"glenn" <gl***@tangelosoftware.netwrites:
>Bruno Desthuilliers wrote:
>>It might be better to use newstyle classes if you can. Also, the
convention is to use CamelCase for classes names (unless you have
a strong reason to do otherwise).

Note that this style is more correctly called TitleCase, since the
first letter of *every* word is capitalised, like in a headline (or
title). "camel case" is different -- see below.
Oops, sorry - my mistake.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #13
glenn wrote:
Bruno Desthuilliers wrote:
(snip)
>>
Here you could use a class attribute to provide a default:

class Creature(object):
noise = ""

def voice(self):
return "voice:" + self.noise
class Dog(Creature):
noise="bark"

def voice(self):
print "brace your self:"
return Creature.voice(self)
# can also use this instead, cf the Fine Manual
return super(Dog, self).voice()
(snip)
so for your $.02 do you see this as being, umm, superior in anyway to
creature.voice()?
I suppose "this" refers to the use of super() ? If so, I wouldn't say
it's "superior", but it can be helpful with complex inheritence scheme
(something that does'nt happen very frequently in Python), and more
specifically with multiple inheritance. You may want to read this for
more infos:

http://www.python.org/download/relea...escrintro/#mro

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #14
>
Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...
lol - actually Im confused about this - there seem to be cases where
instantiaing with:
instance=module.classname()
gives me an error, but
instance=module.classname
doesnt - so I got into that habit, except for where I had a constructor
with parameters - except now Im feeling foolish because I cant
replicate the error - which suggests I didnt understand the error
message properly in the first place... arrgh
I guess thats just part of the process of gaining a new language.

glenn

Aug 30 '06 #15
thanks - interesting essay/article - a lot in their I've never really
considered - though its only recently ive started playing with multiple
inheritance in any context - thanks for that
Bruno Desthuilliers wrote:
glenn wrote:
Bruno Desthuilliers wrote:
(snip)
>
Here you could use a class attribute to provide a default:

class Creature(object):
noise = ""

def voice(self):
return "voice:" + self.noise
class Dog(Creature):
noise="bark"

def voice(self):
print "brace your self:"
return Creature.voice(self)
# can also use this instead, cf the Fine Manual
return super(Dog, self).voice()
(snip)
so for your $.02 do you see this as being, umm, superior in anyway to
creature.voice()?

I suppose "this" refers to the use of super() ? If so, I wouldn't say
it's "superior", but it can be helpful with complex inheritence scheme
(something that does'nt happen very frequently in Python), and more
specifically with multiple inheritance. You may want to read this for
more infos:

http://www.python.org/download/relea...escrintro/#mro

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #16
glenn wrote:
>Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...
lol - actually Im confused about this - there seem to be cases where
instantiaing with:
instance=module.classname()
gives me an error, but
instance=module.classname
doesnt - so I got into that habit, except for where I had a constructor
with parameters - except now Im feeling foolish because I cant
replicate the error - which suggests I didnt understand the error
message properly in the first place... arrgh
I guess thats just part of the process of gaining a new language.

glenn
module.classname and module.classname() are two different things. If you
use module.classname() you invoke the __new__ and __init__ methods in
the class, and you might get an error from them.

On the other hand module.classname will always work, assuming classname
really exists in module. What you get back is a sort of reference to the
class itself and not an instance of it.

Aug 30 '06 #17
glenn wrote:
>Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...
lol - actually Im confused about this - there seem to be cases where
instantiaing with:
instance=module.classname()
gives me an error, but
instance=module.classname
doesnt -
These two syntaxes are both legal, but yield different results.
<short>
You *have* to use "instance=module.classname()" to instanciate
module.classname. Else what you get is the class itself, not an instance
of it.
</short>

<longer>
In Python, everything (including modules, classes and functions) is an
object.

The dot ('.') is a 'lookup' operator - 'someobj.someattr' tries to
retrieve attribute 'someattr' from object 'someobj' (according to lookup
rules that are explained in the doc) - whatever that attribute is. So
the expression 'module.classname' yields the attribute 'classname' of
object 'module' (or raise an AttributeError). Execution of the statement
'instance = module.classname' binds the name 'instance' to whatever
expression 'module.classname' yielded - in you case, the class object,
not an instance of it.

Now functions and classes are "callable" objects - which means they
implement the __call__(self, ...) magic method, so you can apply the
call operator to them. Classes are actually callable objects acting as
factory for instances (ie: calling a class object returns an instance of
that class). The expression "someobj.someattr()" *first* lookup for
attribute 'someattr' of object 'someobj', *then* call it.
</longer>
so I got into that habit, except for where I had a constructor
with parameters
Programming by accident is a well-known antipattern.
- except now Im feeling foolish because I cant
replicate the error - which suggests I didnt understand the error
message properly in the first place...
And that you misunderstood a very important point of Python's syntax.
The call operator (ie parenthesis) is *not* optional.
arrgh
I guess thats just part of the process of gaining a new language.
Probably, yes !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #18
glenn wrote:
>>Bruno Desthuilliers wrote:

http://www.python.org/download/relea...escrintro/#mro
thanks - interesting essay/article - a lot in their I've never really
considered - though its only recently ive started playing with multiple
inheritance in any context - thanks for that
While you're at it (and if not done yet), take some times to read the
whole article - mro is only a little part of the whole thing.
Understanding lookup rules and the descriptor protocol can be of great help.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 30 '06 #19
Chaz Ginger wrote:
glenn wrote:
>>Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...
lol - actually Im confused about this - there seem to be cases where
instantiaing with:
instance=module.classname()
gives me an error, but
instance=module.classname
doesnt - so I got into that habit, except for where I had a constructor
with parameters - except now Im feeling foolish because I cant
replicate the error - which suggests I didnt understand the error
message properly in the first place... arrgh
I guess thats just part of the process of gaining a new language.

glenn

module.classname and module.classname() are two different things. If you
use module.classname() you invoke the __new__ and __init__ methods in
the class, and you might get an error from them.

On the other hand module.classname will always work, assuming classname
really exists in module. What you get back is a sort of reference to the
class itself and not an instance of it.
It is not a sort of reference to the class, it is *the class itself*.
>>class A:
.... pass
....
>>A
<class __main__.A at 0xdeadbeef>
>>>
Georg
Aug 30 '06 #20
Georg Brandl wrote:
Chaz Ginger wrote:
>glenn wrote:
>>>Shouldn't that be

beagle = animal.dog()

to create an instance?

We've all done it ...
lol - actually Im confused about this - there seem to be cases where
instantiaing with:
instance=module.classname()
gives me an error, but
instance=module.classname
doesnt - so I got into that habit, except for where I had a constructor
with parameters - except now Im feeling foolish because I cant
replicate the error - which suggests I didnt understand the error
message properly in the first place... arrgh
I guess thats just part of the process of gaining a new language.

glenn

module.classname and module.classname() are two different things. If
you use module.classname() you invoke the __new__ and __init__ methods
in the class, and you might get an error from them.

On the other hand module.classname will always work, assuming
classname really exists in module. What you get back is a sort of
reference to the class itself and not an instance of it.

It is not a sort of reference to the class, it is *the class itself*.
>>class A:
... pass
...
>>A
<class __main__.A at 0xdeadbeef>
>>>

Georg
A reference by any other name still smells as sweet! lol.
Aug 30 '06 #21
Bruno Desthuilliers <on***@xiludom.growrote:
I suppose "this" refers to the use of super() ? If so, I wouldn't say
it's "superior", but it can be helpful with complex inheritence scheme
.... which aren't anywhere in sight. Don't start using super() until you
need diamond shape inheritance (not counting object as base) and
can be sure that *all* involved classes use super().

While I don't agree with the word "harmful", googling for "python",
"super" and "harmful" will give you deeper insights to this (and
GvR's reaction, too).

Cheers,
--Jan Niklas
Aug 30 '06 #22

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

Similar topics

8
by: Bryan Parkoff | last post by:
I find an interesting issue that one base class has only one copy for each derived class. It looks like that one base class will be copied into three base classes while derived class from base...
5
by: Nathan Bullock | last post by:
Hi, I have a base class, say Base and there are two classes, say Class1 and Class2 which are derived from Base. Is there any way for me, say from a static method in Base, to get a list of all...
13
by: z. f. | last post by:
Hi, i have a class that is derived from System.Web.UI.Page, and this is the class i use in my application as PageBase. all other page classes are deriverd from my PageBase instead of the...
9
by: Sean Kirkpatrick | last post by:
To my eye, there doesn't seem to be a whole lot of difference between the two of them from a functional point of view. Can someone give me a good explanation of why one vs the other? Sean
5
by: eiji | last post by:
Hi folks, I hope this is not "off topic"! :-) Consider the next code: /* Declarations of types that could become platform-dependent */ #define MyChar char #define MyInt int
8
by: Jackson | last post by:
I want a class that will determine its base class by the argument passed in. What I am about to write _does_not_work_, but it shows what I am trying to do. class ABC(some_super): def...
26
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is...
15
by: Bob Johnson | last post by:
I have a base class that must have a member variable populated by, and only by, derived classes. It appears that if I declare the variable as "internal protected" then the base class *can*...
2
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.