473,749 Members | 2,384 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OO in Python? ^^

Hi,

sorry for my ignorance, but after reading the Python tutorial on
python.org, I'm sort of, well surprised about the lack of OOP
capabilities in python. Honestly, I don't even see the point at all of
how OO actually works in Python.

For one, is there any good reason why I should ever inherit from a
class? ^^ There is no functionality to check if a subclass correctly
implements an inherited interface and polymorphism seems to be missing
in Python as well. I kind of can't imagine in which circumstances
inheritance in Python helps. For example:

class Base:
def foo(self): # I'd like to say that children must implement foo
pass

class Child(Base):
pass # works

Does inheritance in Python boil down to a mere code sharing?

And how do I formulate polymorphism in Python? Example:

class D1(Base):
def foo(self):
print "D1"

class D2(Base):
def foo(self):
print "D2"

obj = Base() # I want a base class reference which is polymorphic
if (<need D1>):
obj = D1()
else:
obj = D2()

I could as well leave the whole inheritance stuff out and the program
would still work (?).

Please give me hope that Python is still worth learning :-/

Regards,
Matthias
Dec 10 '05 #1
86 4086
Matthias Kaeppler wrote:
<snip a whole lot of talk of someone still thinking in terms of C>


Let this enlighten your way, young padawan:

modelnine@phoen ix ~/gtk-gnutella-downloads $ python
Python 2.4.2 (#1, Oct 31 2005, 17:45:13)
[GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
import this The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


And, _do_ (don't only read) the tutorial, and you'll understand why the
short example code you posted isn't pythonic, to say the least:
http://www.python.org/doc/2.4.2/tut/tut.html
and why inheritance in Python is necessary, but on a whole different level
of what you're thinking.

Oh, and on a last note, if you're german, you might as well join
de.comp.lang.py thon.

--- Heiko.
Dec 10 '05 #2
Matthias Kaeppler wrote:
polymorphism seems to be missing in Python


QOTW!

</F>

Dec 10 '05 #3
Matthias Kaeppler wrote:
class Base:
def foo(self): # I'd like to say that children must implement foo
pass
def foo(self):
raise NotImplementedE rror("Subclasse s must implement foo")

Now calling foo on a child instance will fail if it hasn't implemented foo.
And how do I formulate polymorphism in Python? Example:

class D1(Base):
def foo(self):
print "D1"

class D2(Base):
def foo(self):
print "D2"
obj = Base() # I want a base class reference which is polymorphic
if (<need D1>):
obj = D1()
else:
obj = D2()


I have no idea what you're trying to do here and how it relates to
polymorphism.

--
Brian Beck
Adventurer of the First Order
Dec 10 '05 #4
Fredrik Lundh wrote:
Matthias Kaeppler wrote:
polymorphism seems to be missing in Python


QOTW!


Let's have some UQOTW: the un-quote of the week! ;-)

--- Heiko.
Dec 10 '05 #5
Brian Beck wrote:

class D1(Base):
def foo(self):
print "D1"

class D2(Base):
def foo(self):
print "D2"
obj = Base() # I want a base class reference which is polymorphic
if (<need D1>):
obj = D1()
else:
obj = D2()


I have no idea what you're trying to do here and how it relates to
polymorphism.


He's translating C++ code directly to Python. obj = Base() creates a
variable of type Base(), to which you can assign different object types (D
(), D2()) which implement the Base interface (are derived from Base).
Err... At least I think it's what this code is supposed to mean...

In C++ you'd do:

Base *baseob;

if( <i want d1> ) {
baseob = (Base*)new D1();
} else {
baseob = (Base*)new D2();
}

baseob->foo();

(should, if foo is declared virtual in Base, produce "d1" for D1, and "d2"
for D2)

At least IIRC, it's been quite some time since I programmed C++... ;-)
*shudder*

--- Heiko.
Dec 10 '05 #6
In article <dn************ *@news.t-online.com>,
Matthias Kaeppler <vo**@void.co m> wrote:
...
obj = Base() # I want a base class reference which is polymorphic
obj now refers to an instance of Base.
if (<need D1>):
obj = D1()
obj now refers to an instance of D1(). The Base instance is
unreferenced.
else:
obj = D2()
obj now refers to an instance of D2(). The Base instance is
unreferenced.

Note that there is no code path that results in obj still referring to
an instance of Base. Unless making a Base had side effects, there is no
use in the first line.

I could as well leave the whole inheritance stuff out and the program
would still work (?).
That program might.

Please give me hope that Python is still worth learning :-/


Python has inheritance and polymorphism, implemented via dictionaries.
Python's various types of namespace are implemented with dictionaries.

Type this in to the Python interpreter:

class Base:
def foo(self):
print 'in Base.foo'

class D1(Base):
def foo(self):
print 'in D1.foo'
Base.foo(self)

class D2(Base):
def foo(self):
print 'in D2.foo'
Base.foo(self)

def makeObj():
return needD1 and D1() or D2()

needD1 = True
makeObj().foo()

needD1 = False
makeObj().foo()
_______________ _______________ _______________ _______________ ____________
TonyN.:' *firstname*nlsn ews@georgea*las tname*.com
' <http://www.georgeanels on.com/>
Dec 10 '05 #7
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
> "Matthias" == Matthias Kaeppler <vo**@void.co m> writes:

Matthias> sorry for my ignorance, but after reading the Python
Matthias> tutorial on python.org, I'm sort of, well surprised about
Matthias> the lack of OOP capabilities in python. Honestly, I don't
Matthias> even see the point at all of how OO actually works in
Matthias> Python.

It's very common for Python newbies, especially those with backgrounds
in languages such as C++, Java etc. to not really 'get' the Python way
of handling types until they've had a fair amount of experience with
Python. If you want to program Pythonically, you must first unlearn a
number of things.

For instance, in e.g. the Java tradition, if a function needs a
triangle object, it'll take a triangle object as an argument. If it
can handle any type of shape, it'll either take a shape base class
instance as an argument or there'll be some kind of shape interface that
it can take. Argument types are strictly controlled. Not so with
Python. A Python solution will typically take any type of object as an
argument so long as it behaves as expected, and if it doesn't, we deal
with the resulting exception (or don't, depending on what we're trying
to accomplish). For instance, if the function from before that wants a
shape really only needs to call an area method, anything with an area
method can be used successfully as an argument.

Some have dubbed this kind of type check 'duck typing': if it walks
like a duck and quacks like a duck, chances are it'll be a duck. To
those who are used to (more or less) strong, static type checks, this
will seem a reckless approach, but it really works rather well, and
subtle type errors are, in my experience, as rare in Python as in any
other language. In my opinion, the tricks the C*/Java people
occasionally do to get around the type system, such as casting to the
fundamental object type, are worse because they're seldom expected and
resulting errors thus typically more subtle.

In my very first post on this news group a number of years ago, I
asked for an equivalent of Java's interfaces. The only reply I got was
that I didn't need them. While the reason was very obvious, even with
what I knew about Python, it still took a while to sink in. From what
I can tell, you're in somewhat the same situation, and the two of us
are far from unique. As I said in the beginning, Python newbies with a
background in statically typed languages typically have a lot to
unlearn, but in my opinion, it's well worth it.
Martin
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using Mailcrypt+GnuPG <http://www.gnupg.org>

iEYEARECAAYFAkO ba8oACgkQYu1fMm OQldXzcgCg0JEGT EG7xC/yAx8C1VFO8H1R
LWwAnRJ8AxHBe8Y oHcDC5oGRfYaPHT fX
=HdTR
-----END PGP SIGNATURE-----
Dec 11 '05 #8
Heiko Wundram wrote:
Matthias Kaeppler wrote:
<snip a whole lot of talk of someone still thinking in terms of C>

Well, unless you are (or he is) in with the GNOME crowd, C probably
isn't really the object-oriented language acting as inspiration here.

[Zen of Python]

Of course the ZoP (Zen of Python) is deep guidance for those
languishing in some design dilemma or other, but not exactly helpful,
concrete advice in this context. (I'm also getting pretty jaded with
the recent trend of the ZoP being quoted almost once per thread on
comp.lang.pytho n, mostly as a substitute for any real justification of
Python's design or any discussion of the motivations behind its
design.) That said, the questioner does appear to be thinking of
object-oriented programming from a statically-typed perspective, and
I'd agree that, ZoP or otherwise, a change in perspective and a
willingness to accept other, equally legitimate approaches to
object-orientation will lead to a deeper understanding and appreciation
of the Python language.

Anyway, it appears that the questioner is confusing declarations with
instantiation, amongst other things:
And how do I formulate polymorphism in Python? Example:

class D1(Base):
def foo(self):
print "D1"

class D2(Base):
def foo(self):
print "D2"

obj = Base() # I want a base class reference which is polymorphic
Well, here one actually gets a reference to a Base object. I know that
in C++ or Java, you'd say, "I don't care exactly what kind of Base-like
object I have right now, but I want to be able to hold a reference to
one." But in Python, this statement is redundant: names/variables
potentially refer to objects of any type; one doesn't need to declare
what type of objects a name will refer to.
if (<need D1>):
obj = D1()
else:
obj = D2()
Without the above "declaratio n", this will just work. If one needs an
instance of D1, one will assign a new D1 object to obj; otherwise, one
will assign a new D2 object to obj. Now, when one calls the foo method
on obj, Python will just find whichever implementation of that method
exists on obj and call it. In fact, when one does call the method, some
time later in the program, the object held by obj doesn't even need to
be instantiated from a related class: as long as the foo method exists,
Python will attempt to invoke it, and this will even succeed if the
arguments are compatible.

All this is quite different to various other object-oriented languages
because many of them use other mechanisms to find out whether such a
method exists for any object referred to by the obj variable. With such
languages, defining a base class with the foo method and defining
subclasses with that method all helps the compiler to determine whether
it is possible to find such a method on an object referred to by obj.
Python bypasses most of that by doing a run-time check and actually
looking at what methods are available just at the point in time a
method is being called.
I could as well leave the whole inheritance stuff out and the program would still work
(?).
Correct. Rewinding...
Does inheritance in Python boil down to a mere code sharing?


In Python, inheritance is arguably most useful for "code sharing", yes.
That said, things like mix-in classes show that this isn't as
uninteresting as one might think.

Paul

Dec 11 '05 #9
Heiko Wundram wrote:
Fredrik Lundh wrote:
Matthias Kaeppler wrote:
polymorphi sm seems to be missing in Python


QOTW!


Let's have some UQOTW: the un-quote of the week! ;-)


+1
Dec 11 '05 #10

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

Similar topics

0
8832
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
9566
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...
1
9333
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,...
1
6800
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
6078
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
4608
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
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3319
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
3
2217
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.