[newbie] Looking for a good introduction to object orientedprogramming with Python

J

Jean Dubois

I'm looking for a good introduction to object oriented programming
with Python. I am looking for an introduction which only refers to
Python. I have seen introductions where the authors make comparisons
to other languages such as C++ and Java, but as I don't know these
languages that doesn't help me further much, it rather confuses me. I
also found an introduction in which the author started by telling that
"object oriented programming is weird", such a statement did stop me
reading further as I think an author should at least believe in the
topic he is going to present as being logical.
If someone here has a link or title to such an intro, I'd appreciate
that very much

regards,
Jean
p.s. People who don't like my style of asking questions, please
neglect this message
 
S

shearichard

One reason you may be having difficulty is that unlike some languages (C++/Java) object-orientation is not a be all and end all in Python, in fact youcould work with Python for a long time without really 'doing it' at all (well other than calling methods/properties on existing API's). Having said that here's what I would suggest ...

Could do worse than this :

http://www.diveintopython.net/object_oriented_framework/index.html

and this

http://docs.python.org/tutorial/classes.html

read together.

Judging by your question this is a probably a little advanced for now but you could bookmark it for the future:

http://www.catonmat.net/blog/learning-python-design-patterns-through-video-lectures/

Here's the corresponding PDF to go with the video:

http://assets.en.oreilly.com/1/event/45/Practical Python Patterns Presentation.pdf
 
J

Jean Dubois

One reason you may be having difficulty is that unlike some languages (C++/Java) object-orientation is not a be all and end all in Python, in fact you could work with Python for a long time without really 'doing it' at all (well other than calling methods/properties on existing API's). Having saidthat here's what I would suggest ...

Could do worse than this :

http://www.diveintopython.net/object_oriented_framework/index.html

and this

http://docs.python.org/tutorial/classes.html

read together.

Judging by your question this is a probably a little advanced for now butyou could bookmark it for the future:

http://www.catonmat.net/blog/learning-python-design-patterns-through-...

Here's the corresponding PDF to go with the video:

http://assets.en.oreilly.com/1/event/45/Practical Python Patterns...

Thanks a lot for this information, I'll check it out the following
days

best regards,
Jean
 
J

Jean Dubois

One reason you may be having difficulty is that unlike some languages (C++/Java) object-orientation is not a be all and end all in Python, in fact you could work with Python for a long time without really 'doing it' at all (well other than calling methods/properties on existing API's). Having saidthat here's what I would suggest ...

Could do worse than this :

http://www.diveintopython.net/object_oriented_framework/index.html
This example seems to tell you need the concept of dictionaries to
explain object oriented programming, is this really necessary?
Unfortunately, the trouble with this explanation is exactly what made
me ask the original question: it starts from concepts in c++ making it
very hard to understand for someone who does not know that language
already.
read together.

Judging by your question this is a probably a little advanced for now butyou could bookmark it for the future:

http://www.catonmat.net/blog/learning-python-design-patterns-through-...

Here's the corresponding PDF to go with the video:

http://assets.en.oreilly.com/1/event/45/Practical Python Patterns...
Can someone here on this list give a trivial example of what object
oriented programming is, using only Python?

thanks in advance
Jean
 
M

Mark Lawrence

This example seems to tell you need the concept of dictionaries to
explain object oriented programming, is this really necessary?
Unfortunately, the trouble with this explanation is exactly what made
me ask the original question: it starts from concepts in c++ making it
very hard to understand for someone who does not know that language
already.
Can someone here on this list give a trivial example of what object
oriented programming is, using only Python?

thanks in advance
Jean

Try this http://www.voidspace.org.uk/python/articles/OOP.shtml ???
 
R

Roy Smith

Jean Dubois said:
Can someone here on this list give a trivial example of what object
oriented programming is, using only Python?

OOP seems to mean different things to different people. What OOP means
to you is usually a strong function of whatever OOP language you learned
first. That being said, I think the fundamental, universal, core
principle of OOP is that an object contains some data, and some code
that knows how to do something with that data.

So, to give you a simple (but real-life) example, the system I'm working
in now has User objects. A user is a pretty complicated class, but
here's some simple methods from it:

def __eq__(self, other):
return isinstance(other, (User, AnonymousUser)) \
and self.user_id == other.user_id

def __unicode__(self):
return self.username

def __repr__(self):
return '<User %d: %r>' % (self.user_id, self.username)

This defines a few basic behaviors for User objects.

First, it defines how to tell if something is equal to a given User
object. The something must itself be a User (ignore the minor
complication about AnonymousUser for the moment), and it must have the
same user_id as this one. I could easily imagine lots of other possible
ways two users could be considered equal (same username, for example),
but we're using user_id. This means I can write:

if user1 == user2:
print "they're the same"

and I don't have to worry about (or even know about) the details. In
fact, sometime long after I've written that code, somebody could define
some new kind of HighSecurityUser which tests for equality by comparing
the scanned retina images for both of them. My code wouldn't have to
change; it would magically just start enforcing retina matching.

Likewise, I can write:

print user

or

logger.warning("%r did something interesting", user)

and I don't have to know anything about how to print a User. The User
knows how to print itself.
 
D

dncarac

I found Mark Lutz's book Learning Python had two or three chapters on object oriented programming from starting principles to more involved Python object programming. It helped me immensely.
 
M

Mark Lawrence

On 05/08/2012 20:46, lipska the kat wrote:

[snip]
There is a book you could try, it's a bit dry and I read it when I can't
sleep, about 30 mins usually does it :)
It's called Design Patterns by Gamma, Helm, Johnson and Vlissides
ISBN 0-201-63361-2.
They do use C++ code in examples but as they say, this is just a
convenience and shouldn't colour your view of the subject
I still read the introduction and get something out of it after several
years. You should be able to implement the patterns in Python
although I must admit I haven't tried that yet

Please no, that's the worst possible book for someone trying to learn
OOD in Python. It's mostly if not completely irrelevant, jumping
through hoops that you don't need in Python because of its dynamic
nature. Start with the factory pattern and I hope you'll understand why
I say this. Search for "design patterns alex martelli" and you'll get
all you need and more.
 
D

Dennis Lee Bieber

Unfortunately, the trouble with this explanation is exactly what made
me ask the original question: it starts from concepts in c++ making it
very hard to understand for someone who does not know that language
already.

Then maybe you are asking the wrong question...

Don't look for Object-Oriented Programming -- since the first widely
popular OOP language was C++ (Smalltalk was earlier, but rather
specialized, whereas C++ started as a preprocessor for C).

Rather look for Object-Oriented Analysis and Design (OOAD). An OOAD
textbook /should/ be language neutral and, these days, likely using the
constructs/notation of UML [which derived from a merger of two or three
separate proposals for OOAD tools]

An OOAD text should cover, besides Classes, Use Cases, state
diagrams, and lots of other things...

The short view of a Class is that it is a means of encapsulating the
methods (functions/operations) of an object along with the attributes
(data) of a specific instance of the class.

A Radio Class would define methods to change the volume, power
state, tuning, and band. These methods are common to all radios. But an
instance of a radio doesn't share its volume level with all other
instances of the Radio class.


OOP is more a style/philosophy of programming by using "objects".
Ada 95 is an OOP language but didn't have the
"object.method(parameters)" syntax (one had to use "method(object,
parameters", but the language could determine which of similar named
methods was meant based upon the type of "object" and the types of the
parameters).
 
S

Steven D'Aprano

Don't look for Object-Oriented Programming -- since the first widely
popular OOP language was C++ (Smalltalk was earlier, but rather
specialized, whereas C++ started as a preprocessor for C).

Rather look for Object-Oriented Analysis and Design (OOAD). An OOAD
textbook /should/ be language neutral and, these days, likely using the
constructs/notation of UML [which derived from a merger of two or three
separate proposals for OOAD tools]

Good lord. I'd rather read C++ than UML. And I can't read C++.
 
R

Roy Smith

Design Patterns by Gamma, Helm, Johnson and Vlissides

Please no, that's the worst possible book for someone trying to learn
OOD in Python.

+1 what Mark said. It's certainly the classic patterns book, but most
of it is about clever ways to work around the C++/Java style of type
bondage. Trying to learn OO from that book is like learning to paint by
reading a textbook on the chemical properties of oil pigments.
 
R

Roy Smith

Steven D'Aprano said:
Don't look for Object-Oriented Programming -- since the first widely
popular OOP language was C++ (Smalltalk was earlier, but rather
specialized, whereas C++ started as a preprocessor for C).

Rather look for Object-Oriented Analysis and Design (OOAD). An OOAD
textbook /should/ be language neutral and, these days, likely using the
constructs/notation of UML [which derived from a merger of two or three
separate proposals for OOAD tools]

Good lord. I'd rather read C++ than UML. And I can't read C++.

UML is under-rated. I certainly don't have any love of the 47 different
flavors of diagram, but the basic idea of having a common graphical
language for describing how objects and classes interact is pretty
useful. Just don't ask me to remember which kind of arrowhead I'm
supposed to use in which situation.
 
M

Mark Lawrence

Steven D'Aprano said:
Don't look for Object-Oriented Programming -- since the first widely
popular OOP language was C++ (Smalltalk was earlier, but rather
specialized, whereas C++ started as a preprocessor for C).

Rather look for Object-Oriented Analysis and Design (OOAD). An OOAD
textbook /should/ be language neutral and, these days, likely using the
constructs/notation of UML [which derived from a merger of two or three
separate proposals for OOAD tools]

Good lord. I'd rather read C++ than UML. And I can't read C++.

UML is under-rated. I certainly don't have any love of the 47 different
flavors of diagram, but the basic idea of having a common graphical
language for describing how objects and classes interact is pretty
useful. Just don't ask me to remember which kind of arrowhead I'm
supposed to use in which situation.

Ask nicely and I'll lend you my copy of Martin Fowler's UML Distilled
which covers "version 1.2 OMG UML standard". What's it up to now,
version 17.38?
 
S

Steven D'Aprano

<rant>
Object Oriented programming is a mindset, a way of looking at that
particular part of our world that you are trying to encapsulate in
computer language. The language you use is (should be) irrelevant.

That depends on how you define OOP, and in particular, which aspects of
OOP your language supports.

There are lots of differences between styles and implementations of OOP
languages, and no two languages have exactly the same feature set, but in
general most OOP languages involve most of the following features:

- Dynamic dispatch when making method calls
- Encapsulation, or multi-methods
- Subtype polymorphism
- Object inheritance, or delegation

See here for more detail:

http://en.wikipedia.org/wiki/Object-oriented_programming#Fundamental_features_and_concepts

But beyond those fundamentals, the details of OOP can differ greatly from
language to language. Some languages treat classes as static, some as
dynamic. Some languages treat classes as objects themselves, others treat
them as non-objects. Syntax varies (although the dot operator has become
almost completely ubiquitous, there are still some exceptions).

In particularly, terminology varies -- I personally despise with the heat
of a thousand suns the terms "instance variable" and "class variable" for
attributes or members. Since a "string variable" is a variable holding a
string, and a "float variable" is a variable holding a float, an instance
variable should be a variable holding an instance, and a class variable
should be a variable holding a class.

The ONLY concept that you should never try to encapsulate is/are human
beings or their aliases. So Person, User, Human etc should not exist in
any way shape or form in your design. There is an argument that User is
ok but I don't subscribe to that.

If you want to represent human interaction in your software design use
Account or Session or some other non human noun. </rant>

Is this some sort of mystical "humans aren't objects, they're SPECIAL!!!"
rubbish? Because it sure sounds like it.

Can you give some non-religious reasons why you should not implement
human beings or aliases as objects?

If not, let me just say that I reject your prohibition and leave it at
that.

Actually it should really be called Class Oriented programming as
classes are the units of encapsulation.

Incorrect. You don't even need classes to have objects. You can have
class-based OOP, and prototype-based OOP, as in Javascript, Actionscript,
Io, and the language which invented the term, Self.

http://en.wikipedia.org/wiki/Prototype-based_programming

I really don't think python is a
good language to learn OO programming, the problem is that Python
doesn't enforce OO so you are never going to learn what is 'OO' and what
isn't.

I think that's exactly why Python *is* a good language to learn OOP,
because you can be productive even while learning. You can start off by
just adding a little bit of OOP syntax to your programs:

response = raw_input("What do you want to do? ")
response = response.lower() # Look ma, I'm using OOP!

while still being primarily procedural. Then you can gradually learn the
terminology ("what's an instance?"), graduate to writing your own
classes, and then finally move on to OOP techniques which some languages
don't even allow, like metaclasses.

Before I get told off/flamed/shouted at I've just started learning
Python and I think it is a great language with a fantastic standard
library. I've already managed to write meaningful code but I haven't
invented a single class yet.

And why do you think this is a problem?

Classes are one possible solution to problems that actually matter. What
matters is the solution, not the mechanism of the solution. "Writing
classes" is just a means to an end (the solution), not the end itself.

There is a book you could try, it's a bit dry and I read it when I can't
sleep, about 30 mins usually does it :) It's called Design Patterns by
Gamma, Helm, Johnson and Vlissides ISBN 0-201-63361-2.
They do use C++ code in examples but as they say, this is just a
convenience and shouldn't colour your view of the subject I still read
the introduction and get something out of it after several years. You
should be able to implement the patterns in Python although I must admit
I haven't tried that yet

Two problems with "Design Patterns" is that many of them are excessively
abstract, and that often they only exist to work around limitations in
the source language (usually C++ or Java).

The first problem means that any half-decent programmer has probably been
using "Design Patterns" for years without realising it, or knowing the
name. I remember writing an "Object Pool" in procedural Pascal in the
1980s to recycle resources, long before the concept was given a name. Not
that I claim to have invented the concept -- I merely copied it from
someone else, who described the technique without giving it a name. Not
that he invented it either.

The emphasis on *names* is just jargon, design patterns are actually just
problem-solving techniques. Sometimes it's useful to have jargon that
everyone recognises, e.g. "factory function" and "singleton" are two I
consistently remember (and I use the first *all the time* and the second
*never*), but often Design Pattern proponents become side-tracked into
finer and finer differences of greater and greater abstraction, at the
expense of clarity.

In my not-so-humble opinion, the popularity of Design Patterns has a lot
to do with the fact that they are so abstract and jargon-ridden that they
have become a badge of membership into an elite. Shorn of their excessive
abstractness, they're not very special. People were writing helper
functions to assemble complex data long before the Builder pattern was
named, and a Facade is just an interface layer.

Learn Python by all means, the interactive mode is particularly fun,just
try and get a good idea of what OO is all about before you start.

As far as I am concerned, any language without an interactive interpreter
is incomplete.
 
S

Steven D'Aprano

UML is under-rated. I certainly don't have any love of the 47 different
flavors of diagram, but the basic idea of having a common graphical
language for describing how objects and classes interact is pretty
useful. Just don't ask me to remember which kind of arrowhead I'm
supposed to use in which situation.


I frequently draw diagrams to understand the relationships between my
classes and the problem I am trying to solve. I almost invariably use one
type of box and one type of arrowhead. Sometimes if I'm bored I draw
doodles on the diagram. If only I could remember to be consistent about
what doodle I draw where, I too could be an UML guru.
 
D

Dan Sommers

I frequently draw diagrams to understand the relationships between my
classes and the problem I am trying to solve. I almost invariably use one
type of box and one type of arrowhead. Sometimes if I'm bored I draw
doodles on the diagram. If only I could remember to be consistent about
what doodle I draw where, I too could be an UML guru.

+1
 
M

Mark Lawrence

On 06/08/2012 01:22, Steven D'Aprano wrote:

[snipped to death]
In my not-so-humble opinion, the popularity of Design Patterns has a lot
to do with the fact that they are so abstract and jargon-ridden that they
have become a badge of membership into an elite. Shorn of their excessive
abstractness, they're not very special. People were writing helper
functions to assemble complex data long before the Builder pattern was
named, and a Facade is just an interface layer.

Design patterns being abstract and jargon ridden puts them alongside
many other aspects of ICT, CS, call it what you like. Especially
beloved by consultants as it means they can talk crap for hours and
charge a fortune for it.
 
D

Dennis Lee Bieber

Is this some sort of mystical "humans aren't objects, they're SPECIAL!!!"
rubbish? Because it sure sounds like it.

Can you give some non-religious reasons why you should not implement
human beings or aliases as objects?

I think it's an over-simplification of humans being "actors" who
drive the software, and not something ("chess pieces") that the software
should be driving. (OTOH: how many remember that surge in "up-shift"
indicator lights on manual transmission cars, near the late 70s early
80s? The few times I drove one of those, it was telling me to up-shift
as soon as I let out the clutch from the previous up-shift).

Though to me, that really means there should be no requirements
phrased as "the operator shall <do something to the software>"; it
should be "the software shall <respond to operator activity>".

Taken literally, the prohibition would mean no modeling of Employees
in a payroll or HR system -- since Employee represents a person working
for the company.
The emphasis on *names* is just jargon, design patterns are actually just
problem-solving techniques. Sometimes it's useful to have jargon that
everyone recognises, e.g. "factory function" and "singleton" are two I
consistently remember (and I use the first *all the time* and the second
*never*), but often Design Pattern proponents become side-tracked into
finer and finer differences of greater and greater abstraction, at the
expense of clarity.
While I've probably used singletons (usually as sentinels in queues,
I suspect), but can't say that I've ever used a "factory function"...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top