473,772 Members | 3,786 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 4098
Paul Boddie <pa**@boddie.or g.uk> wrote:
...
offer some kind of solution to that problem. Moreover, Python also lets
you define double-underscore attribute names which behave give instance
attributes privacy in all respects, being invisible to users of the
instances concerned, accessible only within methods belonging to the
defining class, and safely overloadable in subclasses without incurring
conflicts.


Unfortunately, that depends on the subclasses' naming:

in module bah.py:
class Foo(object) ...

in module zot.py:
import bah
class Foo(bah.Foo) ...

and alas, the "privacy in all respects" breaks down. Now, the idea of
"class Foo(bah.Foo)" may look silly with such artificial names, but it
IS somewhat likely to happen in the real world when the classes' names
are meaningful. I guess pychecker or the like might check for this and
issue a warning if needed... but I do wish we had better ways to prevent
accidental naming conflicts (not that I can easily think of any).
Alex
Dec 11 '05 #41
Matthias Kaeppler a écrit :
(snip)
I stumbled over this paragraph in "Python is not Java", can anyone
elaborate on it:

"In Java, you have to use getters and setters because using public
fields gives you no opportunity to go back and change your mind later to
using getters and setters. So in Java, you might as well get the chore
out of the way up front. In Python, this is silly, because you can start
with a normal attribute and change your mind at any time, without
affecting any clients of the class. So, don't write getters and setters."

Why would I want to use an attribute in Python, where I would use
getters and setters in Java?
Because you don't *need* getters/setters - you already got'em for free
(more on this latter).
I know that encapsulation is actually just
a hack in Python (common, "hiding" an implementation detail by prefixing
it with the classname so you can't access it by its name anymore? Gimme
a break...),
You're confusing encapsulation with information hiding. The mechanism
you're refering to is not meant to 'hide' anything, only to prevent
accidental shadowing of some attributes. The common idiom for
"informatio n hiding" in Python is to prefix 'protected' attributes with
a single underscore. This warns developers using your code that this is
implementation detail, and that there on their own if they start messing
with it. And - as incredible as this can be - that's enough.

True, this won't stop stupid programmers from doing stupid thing - but
no language is 'idiot-proof' anyway (know the old '#define private
public' C++ trick ?), so why worry ?
but is that a reason to only write white box classes? ^^


First, what is a 'white box' class ?

public class WhiteBox {
protected integer foo;
protected integer bar;

public integer getFoo() {
return foo;
}
public void setFoo(integer newfoo) {
foo = newfoo;
}
public integer getBar() {
return bar;
}
public void setBar(integer newbar) {
bar = newbar;
}
}

Does this really qualify as a 'blackbox' ? Of course not, everything is
publicly exposed. You could have the exact same result (and much less
code) with public attributes.

Now what is the reason to write getters and setters ? Answer : so you
can change the implementation without breaking the API, right ?

Python has something named 'descriptors'. This is a mechanism that is
used for attribute lookup (notice that everything being an object,
methods are attributes too). You don't usually need to worry about it
(you should read about if you really want to understand Python's object
model), but you can still use it when you need to take control over
attribute access. One of the simplest application is 'properties' (aka
computed attributes), and here's an exemple :

class Foo(object):
def __init__(self, bar, baaz):
self.bar = bar
self._baaz = baaz

def _getbaaz(self):
return self._baaz

baaz = Property(fget=_ getbaaz)

This is why you don't need explicit getters/setters in Python : they're
already there ! And you can of course change how they are implemented
without breaking the interface. Now *this* is encapsulation - and it
doesn't need much information hiding...
Dec 11 '05 #42
"Paul Boddie" <pa**@boddie.or g.uk> writes:
One classic example of a
weakly-typed language is BCPL, apparently, but hardly anyone has any
familiarity with it any more.


Actually, BCPL is what Stevenn D'Aprano called "untyped". Except his
definition is suitable for after everyone followed IBM's footsteps in
building general-purpose byte-addressable machines.

In BCPL, everything is a word. Given a word, you can dereference it,
add it to another word (as either a floating point value or an integer
value), or call it as a function.

A classic example of a weakly-typed language would be a grandchild of
BCPL, v6 C. Since then, C has gotten steadily more strongly typed. A
standard complaint as people tried to move code from a v6 C compiler
(even the photo7 compiler) to the v7 compiler was "What do you mean I
can't ....". Of course, hardly anyone has familiarity with that any
more, either.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 11 '05 #43
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
Of course, the IT world is full of people writing code and not testing
it, or at least not testing it correctly. That's why there are frequent
updates or upgrades to software that break features that worked in the
older version. That would be impossible in a test-driven methodology, at
least impossible to do by accident.


That sentence is only true if your tests are bug-free. If not, it's
possible to make a change that introduces a bug that passes testing
because of a bug in the tests. Since tests are code, they're never
bug-free. I will agree that the frequency of upgrades/updates breaking
things means testing isn't being done properly.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 11 '05 #44
Bruno Desthuilliers <bd************ *****@free.quel quepart.fr> writes:
^^ There is no functionality to check if a subclass correctly
implements an inherited interface


I don't know of any language that provide such a thing. At least for
my definition of "correctly" .


Well, since your definition of "correclty" is uknown, I won't use
it. I will point out that the stated goal is impossible for some
reasonable definitions of "correctly" .

My definition of "correctly" is "meets the published contracts for the
methods." Languages with good support for design by contract will
insure that subclasses either correctly implement the published
contracts, or raise an exception when they fail to do so. They do that
by checking the contracts for the super classes in an appropriate
logical relationship, and raising an exception if the contract isn't
met.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 11 '05 #45
On Mon, 12 Dec 2005, Steven D'Aprano wrote:
On Sun, 11 Dec 2005 05:48:00 -0800, bonono wrote:
And I don't think Haskell make the programmer do a lot of work(just
because of its static type checking at compile time).
I could be wrong, but I think Haskell is *strongly* typed (just like
Python), not *statically* typed.


Haskell is strongly and statically typed - very strongly and very
statically!

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
(using Guido's notation):

def f(x: int) -> int:
return 1 + x

Note that this still buys you type safety:

def g(a, b):
c = "{" + a + "}"
d = 1 + b
return c + d

The compiler works out that c must be a string and d must be an int, then,
when it gets to the last line, finds an expression that must be wrong, and
refuses to accept the code.

This sounds like it wouldn't work for complex code, but somehow, it does.
And somehow, it works for:

def f(x):
return x + 1

Too. I think this is due to the lack of polymorphic operator overloading.

A key thing is that Haskell supports, and makes enormous use of, a
powerful system of generic types; with:

def h(a):
return a + a

There's no way to infer concrete types for h or a, so Haskell gets
generic; it says "okay, so i don't know what type a is, but it's got to be
something, so let's call it alpha; we're adding two alphas, and one thing
i know about adding is that adding two things of some type makes a new
thing of that type, so the type of some-alpha + some-alpha is alpha, so
this function returns an alpha". ISTR that alpha gets written 'a, so this
function is:

def h(a: 'a) -> 'a:
return a + a

Although that syntax might be from ML. This extends to more complex
cases, like:

def i(a, b):
return [a, b]

In Haskell, you can only make lists of a homogenous type, so the compiler
deduces that, although it doesn't know what type a and b are, they must be
the same type, and the return value is a list of that type:

def i(a: 'a, b: 'a) -> ['a]:
return [a, b]

And so on. I don't know Haskell, but i've had long conversations with a
friend who does, which is where i've got this from. IANACS, and this could
all be entirely wrong!
At least the "What Is Haskell?" page at haskell.org describes the
language as strongly typed, non-strict, and allowing polymorphic typing.


When applied to functional languages, 'strict' (or 'eager'), ie that
expressions are evaluated as soon as they are formed; 'non-strict' (or
'lazy') means that expressions can hang around as expressions for a while,
or even not be evaluated all in one go. Laziness is really a property of
the implementation, not the the language - in an idealised pure functional
language, i believe that a program can't actually tell whether the
implementation is eager or lazy. However, it matters in practice, since a
lazy language can do things like manipulate infinite lists.

tom

--
ø¤º°`°º¤ø,,,,ø¤ º°`°º¤ø,,,,ø¤º° `°º¤ø,,,,ø¤º°`° º¤ø
Dec 12 '05 #46
Mike Meyer <mw*@mired.or g> wrote:
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
Of course, the IT world is full of people writing code and not testing
it, or at least not testing it correctly. That's why there are frequent
updates or upgrades to software that break features that worked in the
older version. That would be impossible in a test-driven methodology, at
least impossible to do by accident.


That sentence is only true if your tests are bug-free. If not, it's
possible to make a change that introduces a bug that passes testing
because of a bug in the tests. Since tests are code, they're never
bug-free. I will agree that the frequency of upgrades/updates breaking
things means testing isn't being done properly.


Yours is a good point: let's be careful not to oversell or overhype TDD,
which (while great) is not a silver bullet. Specifically, TDD is prone
to a "common-mode failure" between tests and code: misunderstandin g of
the specs (generally underspecified specs); since the writer of the test
and of the code is the same person, if that person has such a
misunderstandin g it will be reflected equally in both code and test.

Which is (part of) why code developed by TDD, while more robust against
many failure modes than code developed more traditionally, STILL needs
code inspection (or pair programming), integration tests, system tests,
and customer acceptance tests (not to mention regression tests, once
bugs are caught and fixed;-), just as much as code developed otherwise.
Alex
Dec 12 '05 #47
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;-).
Alex
Dec 12 '05 #48
On Mon, 12 Dec 2005 01:12:26 +0000, Tom Anderson <tw**@urchin.ea rth.li> wrote:
tom

--
ø¤º°`°º¤ø,,,,ø ¤º°`°º¤ø,,,,ø¤º °`°º¤ø,,,,ø¤º°` °º¤ø
---910079544-1780890058-1134349946=:302 72--


[OT} (just taking liberties with your sig ;-)
,<@><
°º¤ø,,,,ø¤º°`°º ¤ø,,,,ø¤º°P`°º¤ ø,,y,,ø¤º°t`°º¤ ø,,h,,ø¤º°o`°º¤ ø,,n,,ø¤º°
Regards,
Bengt Richter
Dec 12 '05 #49
Mike Meyer wrote:
Bruno Desthuilliers <bd************ *****@free.quel quepart.fr> writes:
^^ There is no functionality to check if a subclass correctly
implements an inherited interface


I don't know of any language that provide such a thing. At least for
my definition of "correctly" .

Well, since your definition of "correclty" is uknown, I won't use
it.


!-)

My own definition of 'correctly' in this context would be about ensuring
that the implementation respects a given semantic.

But honestly, this was a somewhat trollish assertion, and I'm afraid
forgot to add a smiley here.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Dec 12 '05 #50

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

Similar topics

0
9454
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,...
1
10038
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
9912
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...
1
7460
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
6715
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
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.