473,787 Members | 2,857 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
86 4101
In article <1h************ **************@ mail.comcast.ne t>,
al***@mail.comc ast.net (Alex Martelli) wrote:
Tom Anderson <tw**@urchin.ea rth.li> wrote:
...
Haskell is strongly and statically typed - very strongly and very
statically!


Sure.

However, what it's not is manifestly typed - you don't have to put the
types in yourself; rather, the compiler works it out. For example, if i
wrote code like this (using python syntax):

def f(x):
return 1 + x

The compiler would think "well, he takes some value x, and he adds it to 1
and 1 is an integer, and the only thing you can add to an integer is
another integer, so x must be an integer; he returns whatever 1 + x works
out to, and 1 and x are both integers, and adding two integers makes an
integer, so the return type must be integer", and concludes that you meant


hmmm, not exactly -- Haskell's not QUITE as strongly/rigidly typed as
this... you may have in mind CAML, which AFAIK in all of its variations
(O'CAML being the best-known one) *does* constrain + so that "the only
thing you can add to an integer is another integer". In Haskell, + can
sum any two instances of types which meet typeclass Num -- including at
least floats, as well as integers (you can add more types to a typeclass
by writing the required functions for them, too). Therefore (after
loading in ghci a file with
f x = x + 1
), we can verify...:

*Main> :type f
f :: (Num a) => a -> a
A very minor point, but since the need to use +. and the resulting lack
of polymorphism are part of what keeps me away from O'CAML and makes me
stick to Haskell, I still wanted to make it;-).


But if you try
f x = x + 1.0

it's
f :: (Fractional a) => a -> a

I asserted something like this some time ago here, and was
set straight, I believe by a gentleman from Chalmers. You're
right that addition is polymorphic, but that doesn't mean
that it can be performed on any two instances of Num. I had
constructed a test something like that to check my thinking,
but it turns out that Haskell was able to interpret "1" as
Double, for example -- basically, 1's type is Num too.
If you type the constant (f x = x + (1 :: Int)), the function
type would be (f :: Int -> Int). Basically, it seems (+) has
to resolve to a (single) instance of Num.

Donn Cave, do**@u.washingt on.edu
Dec 12 '05 #51
On Mon, 12 Dec 2005, Bengt Richter wrote:
On Mon, 12 Dec 2005 01:12:26 +0000, Tom Anderson <tw**@urchin.ea rth.li> wrote:
--
ø¤º°`°º¤ø,,,,ø¤ º°`°º¤ø,,,,ø¤º° `°º¤ø,,,,ø¤º°`° º¤ø


[OT} (just taking liberties with your sig ;-)
,<@><
°º¤ø,,,,ø¤º°`°º ¤ø,,,,ø¤º°P`°º¤ ø,,y,,ø¤º°t`°º¤ ø,,h,,ø¤º°o`°º¤ ø,,n,,ø¤º°


The irony is that with my current news-reading setup, i see my own sig as
a row of question marks, seasoned with backticks and commas. Your
modification looks like it's adding a fish; maybe the question marks are a
kelp bed, which the fish is exploring for food.

Hmm. Maybe if i look at it through Google Groups ...

Aaah! Very good!

However, given the context, i think it should be:

,<OO><
°º¤ø,,,,ø¤º°`°º ¤ø,,,,ø¤º°P`°º¤ ø,,y,,ø¤º°t`°º¤ ø,,h,,ø¤º°o`°º¤ ø,,n,,ø¤º°

!

tom

--
limited to concepts that are meta, generic, abstract and philosophical --
IEEE SUO WG
Dec 13 '05 #52
On Mon, 12 Dec 2005, Donn Cave wrote:
In article <1h************ **************@ mail.comcast.ne t>,
al***@mail.comc ast.net (Alex Martelli) wrote:
Tom Anderson <tw**@urchin.ea rth.li> wrote:
...

For example, if i wrote code like this (using python syntax):

def f(x):
return 1 + x

The compiler would think "well, he takes some value x, and he adds it to 1
and 1 is an integer, and the only thing you can add to an integer is
another integer, so x must be an integer; he returns whatever 1 + x works
out to, and 1 and x are both integers, and adding two integers makes an
integer, so the return type must be integer"


hmmm, not exactly -- Haskell's not QUITE as strongly/rigidly typed as
this... you may have in mind CAML, which AFAIK in all of its variations
(O'CAML being the best-known one) *does* constrain + so that "the only
thing you can add to an integer is another integer". In Haskell, + can
sum any two instances of types which meet typeclass Num -- including at
least floats, as well as integers (you can add more types to a typeclass
by writing the required functions for them, too). Therefore (after
loading in ghci a file with
f x = x + 1
), we can verify...:

*Main> :type f
f :: (Num a) => a -> a


But if you try
f x = x + 1.0

it's
f :: (Fractional a) => a -> a

I asserted something like this some time ago here, and was set straight,
I believe by a gentleman from Chalmers. You're right that addition is
polymorphic, but that doesn't mean that it can be performed on any two
instances of Num.


That's what i understand. What it comes down to, i think, is that the
Standard Prelude defines an overloaded + operator:

def __add__(x: int, y: int) -> int:
<primitive operation to add two ints>

def __add__(x: float, y: float) -> float:
<primitive operation to add two floats>

def __add__(x: str, y: str) -> str:
<primitive operation to add two strings>

# etc

So that when the compiler hits the expression "x + 1", it has a finite set
of possible interpretations for '+', of which only one is legal - addition
of two integers to yield an integer. Or rather, given that "1" can be an
int or a float, it decides that x could be either, and so calls it "alpha,
where alpha is a number". Or something.

While we're on the subject of Haskell - if you think python's
syntactically significant whitespace is icky, have a look at Haskell's
'layout' - i almost wet myself in terror when i saw that!

tom

--
limited to concepts that are meta, generic, abstract and philosophical --
IEEE SUO WG
Dec 13 '05 #53

Tom Anderson wrote:
While we're on the subject of Haskell - if you think python's
syntactically significant whitespace is icky, have a look at Haskell's
'layout' - i almost wet myself in terror when i saw that!

Though one doesn't need to use indentation and write everything using
{} in Haskell.

Dec 13 '05 #54
Welcome to Python Matthias. I hope you will enjoy it!

Matthias Kaeppler wrote:
Another thing which is really bugging me about this whole dynamically
typing thing is that it seems very error prone to me:

foo = "some string!"

# ...

if (something_fuba r):
fo = "another string"

Oops, the last 'o' slipped, now we have a different object and the
interpreter will happily continue executing the flawed program.


As an old hardware designer from the space industry, I'm well
aquainted with the idea of adding redundancy to make things
more reliable. I also know that this doesn't come without a
prize. All this stuff you add to detect possible errors might
also introduce new errors, and it takes a lot of time and
effort to implement--time that could be spent on better things.

In fact, the typical solutions that are used to increase the
odds that hardware doesn't fail before its Mean Time To
Failure (MTTF), will significantly lower the chance that it
works much longer than its MTTF! More isn't always better.

While not the same thing, software development is similar.
All that redundancy in typical C++ programs has a high
development cost. Most of the stuff in C++ include files
are repeated in the source code, and the splitting of
code between include and source files mean that a lot of
declarations are far from the definitions. We know that
this is a problem: That's why C++ departed from C's concept
of putting all local declarations in the beginning of
functions. Things that are closely related should be as
close as possible in the code!

The static typing means that you either have to make several
implementations of many algorithms, or you need to work with
those convoluted templates that were added to the language as
an afterthought.

Generally, the more you type, the more you will mistype.
I even suspect that the bug rate grows faster than the
size of the code. If you have to type five times as much,
you will probably make typos five times as many times,
but you also have the problem that the larger amount of
code is more difficult to grasp. It's less likely that
all relevant things are visible on the screen at the same
time etc. You'll make more errors that aren't typos.

Python is designed to allow you to easily write short and
clear programs. Its dynamic typing is a very important
part of that. The important thing isn't that we are
relieved from the boring task of typing type declarations,
but rather that the code we write can be much more generic,
and the coupling between function definitions and function
callers can be looser. This means that we get faster
development and easier maintenace if we learn to use this
right.

Sure, a C++ or Java compiler will discover some mistakes
that would pass through the Python compiler. This is not
a design flaw in Python, it's a direct consequence of its
dynamic nature. Compile time type limitations goes against
the very nature of Python. It's not the checks we try to
avoid--it's the premature restrictions in functionality.

Anyway, I'm sure you know that a successful build with
C++ or Java doesn't imply correct behaviour of your
program.

All software needs to be tested, and if we want to work
effectively and be confident that we don't break things
as we add features or tidy up our code, we need to make
automated tests. There are good tools, such as unittest,
doctest, py.test and TextTest that can help us with that.

If you have proper automated tests, those tests will
capture your mistypings, whether they would have been
caught by a C++ or Java compiler or not. (Well, not if
they are in dead code, but C++/Java won't give you any
intelligent help with that either...)

I've certainly lost time due to mistyped variables now
and then. It's not uncommon that I've actually mistyped
in a way that Java/C++ would never notice (e.g. typed i
instead of j in some nested for loop etc) but sometimes
compile time type checking would have saved time for me.

On the other hand, I'm sure that type declarations on
variables would bring a rigidity to Python that would
cost me much more than I would gain, and with typeless
declarations as in Perl (local x) I would probably
waste more time on adding forgotten declarations (or
removing redundant ones) than I would save time on
noticing the variable mistypings a few seconds before
my unittests catch them. Besides, there are a number
of lint-like tools for Python if you want static code
checks.

As I wrote, the lack of type checking in Python is a
consequence of the very dynamic nature of the language.
A function should assume as little as possible about
its parameters, to be able to function in the broadest
possible scope. Don't add complexity to make you code
support things you don't know of a need for, but take
the chance Python gives you of assuming as little as
possible about your callers and the code you call.

This leads to more flexible and maintainable software.
A design change in your software will probably lead to
much more code changes if you write in C++ than if you
write in Python.

While feature-by-feature comparisions of different
programming languages might have some merit, the only
thing that counts in the end is how the total package
works... I think you'll find that Python is a useful
package, and a good tool in a bigger tool chest.
Dec 13 '05 #55

Magnus Lycka wrote:
The static typing means that you either have to make several
implementations of many algorithms, or you need to work with
those convoluted templates that were added to the language as
an afterthought. I don't see this in Haskell.
While feature-by-feature comparisions of different
programming languages might have some merit, the only
thing that counts in the end is how the total package
works... I think you'll find that Python is a useful
package, and a good tool in a bigger tool chest.

That is very true.

Dec 13 '05 #56
bo****@gmail.co m wrote:
Magnus Lycka wrote:
The static typing means that you either have to make several
implementatio ns of many algorithms, or you need to work with
those convoluted templates that were added to the language as
an afterthought.


I don't see this in Haskell.


No, I was refering to C++ when I talked about templates.

I don't really know Haskell, so I can't really compare it
to Python. A smarter compiler can certainly infer types from
the code and assemble several implementations of an
algorithm, but unless I'm confused, this makes it difficult
to do the kind of dynamic linking / late binding that we do in
Python. How do you compile a dynamic library without locking
library users to specific types?

I don't doubt that it's possible to make a statically typed
language much less assembly like than C++...
Dec 14 '05 #57

Magnus Lycka wrote:
I don't really know Haskell, so I can't really compare it
to Python. A smarter compiler can certainly infer types from
the code and assemble several implementations of an
algorithm, but unless I'm confused, this makes it difficult
to do the kind of dynamic linking / late binding that we do in
Python. How do you compile a dynamic library without locking
library users to specific types?

I don't know. I am learning Haskell(and Python too), long way to go
before I would get into the the usage you mentioned, if ever, be it
Haskell or Python.

Dec 14 '05 #58
bo****@gmail.co m wrote:
Magnus Lycka wrote:
I don't really know Haskell, so I can't really compare it
to Python. A smarter compiler can certainly infer types from
the code and assemble several implementations of an
algorithm, but unless I'm confused, this makes it difficult
to do the kind of dynamic linking / late binding that we do in
Python. How do you compile a dynamic library without locking
library users to specific types?


I don't know. I am learning Haskell(and Python too), long way to go
before I would get into the the usage you mentioned, if ever, be it
Haskell or Python.


Huh? I must have expressed my thoughts badly. This is trivial to
use in Python. You could for instance write a module like this:

### my_module.py ###
import copy

def sum(*args):
result = copy.copy(args[0])
for arg in args[1:]:
result += arg
return result

### end my_module.py ###

Then you can do:
from my_module import sum
sum(1,2,3) 6 sum('a','b','c' ) 'abc' sum([1,2,3],[4,4,4]) [1, 2, 3, 4, 4, 4]


Assume that you didn't use Python, but rather something with
static typing. How could you make a module such as my_module.py,
which is capable of working with any type that supports some
standard copy functionality and the +-operator?
Dec 14 '05 #59

Magnus Lycka wrote:
bo****@gmail.co m wrote:
Magnus Lycka wrote:
I don't really know Haskell, so I can't really compare it
to Python. A smarter compiler can certainly infer types from
the code and assemble several implementations of an
algorithm, but unless I'm confused, this makes it difficult
to do the kind of dynamic linking / late binding that we do in
Python. How do you compile a dynamic library without locking
library users to specific types?


I don't know. I am learning Haskell(and Python too), long way to go
before I would get into the the usage you mentioned, if ever, be it
Haskell or Python.


Huh? I must have expressed my thoughts badly. This is trivial to
use in Python. You could for instance write a module like this:

### my_module.py ###
import copy

def sum(*args):
result = copy.copy(args[0])
for arg in args[1:]:
result += arg
return result

### end my_module.py ###

Then you can do:
>>> from my_module import sum
>>> sum(1,2,3) 6 >>> sum('a','b','c' ) 'abc' >>> sum([1,2,3],[4,4,4]) [1, 2, 3, 4, 4, 4] >>>


Assume that you didn't use Python, but rather something with
static typing. How could you make a module such as my_module.py,
which is capable of working with any type that supports some
standard copy functionality and the +-operator?

Ah, I thought you were talking about DLL or some external library
stuff. In Haskell, it use a concept of type class. Conceptually similar
to the "duck typing" thing in python/ruby. You just delcare the data
type then add an implementation as an instance of a type class that
knows about +/- or copy. The inference engine then would do its work.

I would assume that even in python, there are different implement of
+/- and copy for different object types.

Dec 14 '05 #60

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

Similar topics

0
9655
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
9497
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
10363
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...
0
8993
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
7517
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
5398
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
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
2894
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.