SlideShare a Scribd company logo
from java to python
beating the stockholm syndrome
Javier Arias Losada
@javier_arilos
We are going to compare Java versus Python
through some random topics… but not trying to
be exhaustive or follow any logical patterns…
just aspects I liked, disliked or just caught my
attention.
Disclaimer
1. Some points have been improved in latest versions of Python
and Java
2. Opinions stated are those of the author, Javier Arias
Working since 1997 with OO languages, mainly in
Java and some Smalltalk… one has some rigidness
regarding idioms, mental schemes and patterns…
Python approach to many aspects is different
from Java and tends to be more pragmatic.
verbosity and ease of reading (I)
“(…) when you program, you have to think about how someone will read your
code, not just how a computer will interpret it.”
- Kent Beck
Indentation, expressiveness and idioms, libraries matter.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// do something with line.
}
br.close();
with open(...) as f:
for line in f:
# do something with line
http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java
http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
verbosity and ease of reading (II)
logical expressions & truthy values:
if x and x not in elements:
print ‘done’

if (x != null && !elements.contains(x))
{
System.out.println(“done”);
}
Python seems to be ahead here, improves this productivity?
Usually code is easier to read and maintain in Python.
Refactoring is faster and more secure in Java (static typing
+ advanced IDE’s).
verbosity and ease of reading (III)
method and function definition
An example: parse N lines of a file, searching for a text
Python keyword args: named and optional, default values.
def search(txt, file=’./f.txt’, lines=0):
return 0
Java method overriding: different methods with different
parameters (number and type)
public int search(String txt, String file, Integer lines){
return 0;
}
verbosity and ease of reading (IV)
Lets add optional params in Java:
public int search(String txt, Integer lines){
search(txt, “./f.txt”, lines);
}
public int search(String txt, String file){
search(txt, file, 0);
}
Java’s method signature overriding is very useful for
maintaining functions (and constructors) less cluttered.
verbosity and ease of reading (V)
New Requirement: extend our search function to search for a
client’s name, accept instances of Client class.
public int search(Client client, String file){
search(client.getName(), file);
}
def search(what, file=’./f.txt’, lines=0):
if isinstance(what, Client):
what = what.name
(...)
Results of the exercise:
Java: one core method and three “facilitator” methods.
Python: one method that is caring about type of parameters.
verbosity and ease of reading (VI)
List and dictionary comprehensions
a real example: filtering a dictionary.
filtered_policies = {pol: spr_message.policies[pol]
for pol in _GCM_ALLOWED_POLICIES
if pol in spr_message.policies}
Python Dict and list comprehension are very flexible and
powerful ways of creating lists and dict on the fly.
filteredPolicies = sprMessage.getPolicies().keySet()
.retainAll(GCM_ALLOWED_POLICIES);
Java is usually more verbose and less fluent for this
collection related tasks, but sometimes a well designed API
can do miracles, as in this example.
verbosity and ease of reading (end)
searched google looking for
the shortest tutorials of each language:
As an objective indicator,

Teach yourself Java in 21 minutes:
http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf

Learn Python in 10 minutes:
http://www.stavros.io/tutorials/python/

Python is half as verbose as Java.
If you ignore me, in the time of this talk you can learn both
languages.
Just joking :-)
as object oriented languages (I)
inheritance
Liskov Substitution Principle: If S is a subtype of T, then
objects of type T may be replaced with objects of type S.
Use your code without caring about what type or subtype it is.

Java
simple inheritance.
interfaces.
statically-strongly typed.

Python
multiple inheritance.
dynamically-strongly typed.
as object oriented languages (II)
composition-inheritance-multiple inheritance
“In object-oriented programming, Inheritance is the evil forest (...) deep inside
the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)”
- Learn Python the hard way:

http://bit.ly/O709e9

Java super
super();
super.aMethod();

Python super
super(class, object)
super may not call parent: MRO
A
/

super always call parent.



B

C



/
D

About MRO in Python: http://bit.ly/18RHQBC
as object oriented languages (III)
inheritance
The Circle / Ellipse problem:
➔ In maths, circle is a special case for an ellipse: both axes
are equal
➔ Who should be superclass and subclass?
◆
◆

If Ellipse is the parent: what happens with the Ellipse method that
stretches an axis? what does that mean for Circle instances?
If Circle is the parent, seems counterintuitive and no code reused.

Two ways of thinking about subclassing:
1.
2.

The OO classic view
Pragmatic’s non-taxonomy based approach
as object oriented languages (IV)
inheritance, classic OO view
a subclass is a specialization of a superclass.
Organize your code by taxonomies: "Is-a" relationships. e.g. Dog
is-an Animal.
"Inheritance is the idea that one class is a specialization of another class." Code Complete.

This is what the majority of us do: at least in Java, probably
in Python as well.
as object oriented languages (V)
inheritance, alternative approach
Inheritance as a mechanism for code reuse,
nothing to do with taxonomies.
Raymond Hettinger, Python core developer:

Put the Dog on top,
if the Dog has more code that is useful for Animal

From The art of subclassing, Raymond Hettinger.
"How do you decide which one is on top? There is no principle of specialization. (...) Why do we
subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other
class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.”
http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
as object oriented languages (VI)
polymorphism

[1]

- ad-hoc polymorphism: function overloading [already covered]
- parametric polymorphism: generic type that can handle
different types without worrying about their types.
Java: generics:
List<String> l = new ArrayList<String>();
Python: builtin:
l = []

[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Java: inheritance + interfaces + static typing
public class Duck extends Bird implements Swimmer{
public String quack(){

(...)

public void walk(){

(...)

(...)

Duck donald = new Duck();
donald.walk();
donald.fly();
donald.quack();
donald.swim();
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Python: inheritance + duck typing + protocols
class Duck(Bird):
def quack():
def walk():

(...)
(...)

(...)

donald = Duck()
donald.walk()
donald.fly()
donald.quack()
donald.swim()
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
encapsulation:
OCP (open closed principle) : "software entities (classes, modules,
functions, etc.) should be open for extension, but closed for modification"
http://en.wikipedia.org/wiki/Open/closed_principle

visibility (public, protected, ...), javabeans (Java)
versus
"_", "we are all consenting adults here" (Python)

[1]

Python name mangling.
[1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932.
html
execution model (I)
Python execution model differs from those of Java and C++.

In Python everything is a name bounded to an object.
In Java class lifecycle is
separated in load,
initialization and execution.

In Python, LoC are executed.
No separation between
declaration and execution.

1. Class resolved and loaded.
2. Class is initialized.
3. Code in class used.

Functions (def)
(class)

Modules
Entry points to code well
defined: main

Classes

(import)

Entry points to code are the
same modules
execution model (III)

●

Diferenciate explicit execution from import time execution?

if __name__ == ‘_main__’:
“””your program here”””
execution model (III)
●
●
●

implicit variable declaration
duplicate declarations
parameter default values that are mutable

class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [5]: a = A(p2=3)
In [6]: a.method1(1, 2)
1
In [9]: print a.lastp1
1
In [10]: a2 = A(p1=3)
In [12]: print a2.v3
[2]
In [13]: print a.v3
[2]
execution model (IV)
monkey patching
class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [22]: a = A()
In [23]: a.method1(1, 2)
1
In [24]: def m1(self, p, p2):
print 'modified ' + str
(p)
....:
In [25]: A.method1 = m1
In [26]: a.method1(1, 2)
modified 1

Remember: in Python everything is a name bounded to an object.
wrap up

You solve the problems.
The most important part of
any language is you, the
developer.
No clear winner, today I
prefer Python.

Thanks for attending!

More Related Content

What's hot (20)

PPT
Introduction to Python
Nowell Strite
 
PDF
Introduction to python programming
Srinivas Narasegouda
 
PPT
Python ppt
Mohita Pandey
 
PPTX
Python Tutorial for Beginner
rajkamaltibacademy
 
PDF
Introduction to Python Pandas for Data Analytics
Phoenix
 
PDF
Oop basic concepts
Swarup Kumar Boro
 
PPTX
Python final presentation kirti ppt1
Kirti Verma
 
PDF
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
PPTX
Python-00 | Introduction and installing
Mohd Sajjad
 
PPTX
Basics of python
Jatin Kochhar
 
PDF
Python Tutorial
AkramWaseem
 
PDF
A Featherweight Approach to FOOL
greenwop
 
PPTX
Python Seminar PPT
Shivam Gupta
 
PDF
C++0x :: Introduction to some amazing features
Christian Perone
 
PPTX
Python - Lesson 1
Andrew Frangos
 
PDF
Introduction to python 3
Youhei Sakurai
 
PPTX
Classes And Objects
rahulsahay19
 
PDF
Introduction to python 3 2nd round
Youhei Sakurai
 
PPTX
Introduction about Python by JanBask Training
JanBask Training
 
PDF
Oop
志明 陳
 
Introduction to Python
Nowell Strite
 
Introduction to python programming
Srinivas Narasegouda
 
Python ppt
Mohita Pandey
 
Python Tutorial for Beginner
rajkamaltibacademy
 
Introduction to Python Pandas for Data Analytics
Phoenix
 
Oop basic concepts
Swarup Kumar Boro
 
Python final presentation kirti ppt1
Kirti Verma
 
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
Python-00 | Introduction and installing
Mohd Sajjad
 
Basics of python
Jatin Kochhar
 
Python Tutorial
AkramWaseem
 
A Featherweight Approach to FOOL
greenwop
 
Python Seminar PPT
Shivam Gupta
 
C++0x :: Introduction to some amazing features
Christian Perone
 
Python - Lesson 1
Andrew Frangos
 
Introduction to python 3
Youhei Sakurai
 
Classes And Objects
rahulsahay19
 
Introduction to python 3 2nd round
Youhei Sakurai
 
Introduction about Python by JanBask Training
JanBask Training
 

Viewers also liked (7)

PDF
Java VS Python
Simone Federici
 
PDF
Jython: Integrating Python and Java
Charles Anderson
 
PDF
Ruby vs python
Igor Leroy
 
KEY
Why Learn Python?
Christine Cheung
 
PDF
Closing the gap between Distros(devs) and their Users(ops)
Kris Buytaert
 
PDF
Dev secops opsec, devsec, devops ?
Kris Buytaert
 
PPT
Mixing Python and Java
Andreas Schreiber
 
Java VS Python
Simone Federici
 
Jython: Integrating Python and Java
Charles Anderson
 
Ruby vs python
Igor Leroy
 
Why Learn Python?
Christine Cheung
 
Closing the gap between Distros(devs) and their Users(ops)
Kris Buytaert
 
Dev secops opsec, devsec, devops ?
Kris Buytaert
 
Mixing Python and Java
Andreas Schreiber
 
Ad

Similar to From Java to Python: beating the Stockholm syndrome (20)

PPTX
Python PPT by Sushil Sir.pptx
sushil155005
 
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
hpearl130
 
PPTX
Intro to Python for C# Developers
Sarah Dutkiewicz
 
ODP
Dynamic Python
Chui-Wen Chiu
 
PPTX
python-an-introduction
Shrinivasan T
 
PDF
Python intro
rik0
 
ODP
Programming Under Linux In Python
Marwan Osman
 
ODP
Introduction to Python
tswr
 
PDF
Why I Love Python V2
gsroma
 
PPT
Python Kick Start
Karthik Prakash
 
PPT
Introduction to Python For Diploma Students
SanjaySampat1
 
PDF
What is Python? (Silicon Valley CodeCamp 2015)
wesley chun
 
PPTX
Introduction to Python Programming (Basic)
Arvind Bhave
 
PPT
programming with python ppt
Priyanka Pradhan
 
PDF
What is Python?
wesley chun
 
PPTX
Class 27: Pythonic Objects
David Evans
 
PPT
Intro to Python
petrov
 
PDF
Let's learn python
Jaysinh Shukla
 
ODP
Hands on Session on Python
Sumit Raj
 
Python PPT by Sushil Sir.pptx
sushil155005
 
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
hpearl130
 
Intro to Python for C# Developers
Sarah Dutkiewicz
 
Dynamic Python
Chui-Wen Chiu
 
python-an-introduction
Shrinivasan T
 
Python intro
rik0
 
Programming Under Linux In Python
Marwan Osman
 
Introduction to Python
tswr
 
Why I Love Python V2
gsroma
 
Python Kick Start
Karthik Prakash
 
Introduction to Python For Diploma Students
SanjaySampat1
 
What is Python? (Silicon Valley CodeCamp 2015)
wesley chun
 
Introduction to Python Programming (Basic)
Arvind Bhave
 
programming with python ppt
Priyanka Pradhan
 
What is Python?
wesley chun
 
Class 27: Pythonic Objects
David Evans
 
Intro to Python
petrov
 
Let's learn python
Jaysinh Shukla
 
Hands on Session on Python
Sumit Raj
 
Ad

More from Javier Arias Losada (9)

PDF
Why do lazy developers write beautiful code?
Javier Arias Losada
 
PDF
Europython - Machine Learning for dummies with Python
Javier Arias Losada
 
PDF
Pybcn machine learning for dummies with python
Javier Arias Losada
 
PDF
OSCON - ES6 metaprogramming unleashed
Javier Arias Losada
 
PDF
ES6 metaprogramming unleashed
Javier Arias Losada
 
PPTX
Elastically scalable architectures with microservices. The end of the monolith?
Javier Arias Losada
 
PDF
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Javier Arias Losada
 
PDF
Rabbitmq, amqp Intro - Messaging Patterns
Javier Arias Losada
 
PDF
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
Javier Arias Losada
 
Why do lazy developers write beautiful code?
Javier Arias Losada
 
Europython - Machine Learning for dummies with Python
Javier Arias Losada
 
Pybcn machine learning for dummies with python
Javier Arias Losada
 
OSCON - ES6 metaprogramming unleashed
Javier Arias Losada
 
ES6 metaprogramming unleashed
Javier Arias Losada
 
Elastically scalable architectures with microservices. The end of the monolith?
Javier Arias Losada
 
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Javier Arias Losada
 
Rabbitmq, amqp Intro - Messaging Patterns
Javier Arias Losada
 
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
Javier Arias Losada
 

Recently uploaded (20)

PDF
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
PDF
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
PDF
UiPath vs Other Automation Tools Meeting Presentation.pdf
Tracy Dixon
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
PDF
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
Top Managed Service Providers in Los Angeles
Captain IT
 
UiPath vs Other Automation Tools Meeting Presentation.pdf
Tracy Dixon
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 

From Java to Python: beating the Stockholm syndrome

  • 1. from java to python beating the stockholm syndrome Javier Arias Losada @javier_arilos
  • 2. We are going to compare Java versus Python through some random topics… but not trying to be exhaustive or follow any logical patterns… just aspects I liked, disliked or just caught my attention. Disclaimer 1. Some points have been improved in latest versions of Python and Java 2. Opinions stated are those of the author, Javier Arias
  • 3. Working since 1997 with OO languages, mainly in Java and some Smalltalk… one has some rigidness regarding idioms, mental schemes and patterns… Python approach to many aspects is different from Java and tends to be more pragmatic.
  • 4. verbosity and ease of reading (I) “(…) when you program, you have to think about how someone will read your code, not just how a computer will interpret it.” - Kent Beck Indentation, expressiveness and idioms, libraries matter. BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { // do something with line. } br.close(); with open(...) as f: for line in f: # do something with line http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
  • 5. verbosity and ease of reading (II) logical expressions & truthy values: if x and x not in elements: print ‘done’ if (x != null && !elements.contains(x)) { System.out.println(“done”); } Python seems to be ahead here, improves this productivity? Usually code is easier to read and maintain in Python. Refactoring is faster and more secure in Java (static typing + advanced IDE’s).
  • 6. verbosity and ease of reading (III) method and function definition An example: parse N lines of a file, searching for a text Python keyword args: named and optional, default values. def search(txt, file=’./f.txt’, lines=0): return 0 Java method overriding: different methods with different parameters (number and type) public int search(String txt, String file, Integer lines){ return 0; }
  • 7. verbosity and ease of reading (IV) Lets add optional params in Java: public int search(String txt, Integer lines){ search(txt, “./f.txt”, lines); } public int search(String txt, String file){ search(txt, file, 0); } Java’s method signature overriding is very useful for maintaining functions (and constructors) less cluttered.
  • 8. verbosity and ease of reading (V) New Requirement: extend our search function to search for a client’s name, accept instances of Client class. public int search(Client client, String file){ search(client.getName(), file); } def search(what, file=’./f.txt’, lines=0): if isinstance(what, Client): what = what.name (...) Results of the exercise: Java: one core method and three “facilitator” methods. Python: one method that is caring about type of parameters.
  • 9. verbosity and ease of reading (VI) List and dictionary comprehensions a real example: filtering a dictionary. filtered_policies = {pol: spr_message.policies[pol] for pol in _GCM_ALLOWED_POLICIES if pol in spr_message.policies} Python Dict and list comprehension are very flexible and powerful ways of creating lists and dict on the fly. filteredPolicies = sprMessage.getPolicies().keySet() .retainAll(GCM_ALLOWED_POLICIES); Java is usually more verbose and less fluent for this collection related tasks, but sometimes a well designed API can do miracles, as in this example.
  • 10. verbosity and ease of reading (end) searched google looking for the shortest tutorials of each language: As an objective indicator, Teach yourself Java in 21 minutes: http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf Learn Python in 10 minutes: http://www.stavros.io/tutorials/python/ Python is half as verbose as Java. If you ignore me, in the time of this talk you can learn both languages. Just joking :-)
  • 11. as object oriented languages (I) inheritance Liskov Substitution Principle: If S is a subtype of T, then objects of type T may be replaced with objects of type S. Use your code without caring about what type or subtype it is. Java simple inheritance. interfaces. statically-strongly typed. Python multiple inheritance. dynamically-strongly typed.
  • 12. as object oriented languages (II) composition-inheritance-multiple inheritance “In object-oriented programming, Inheritance is the evil forest (...) deep inside the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)” - Learn Python the hard way: http://bit.ly/O709e9 Java super super(); super.aMethod(); Python super super(class, object) super may not call parent: MRO A / super always call parent. B C / D About MRO in Python: http://bit.ly/18RHQBC
  • 13. as object oriented languages (III) inheritance The Circle / Ellipse problem: ➔ In maths, circle is a special case for an ellipse: both axes are equal ➔ Who should be superclass and subclass? ◆ ◆ If Ellipse is the parent: what happens with the Ellipse method that stretches an axis? what does that mean for Circle instances? If Circle is the parent, seems counterintuitive and no code reused. Two ways of thinking about subclassing: 1. 2. The OO classic view Pragmatic’s non-taxonomy based approach
  • 14. as object oriented languages (IV) inheritance, classic OO view a subclass is a specialization of a superclass. Organize your code by taxonomies: "Is-a" relationships. e.g. Dog is-an Animal. "Inheritance is the idea that one class is a specialization of another class." Code Complete. This is what the majority of us do: at least in Java, probably in Python as well.
  • 15. as object oriented languages (V) inheritance, alternative approach Inheritance as a mechanism for code reuse, nothing to do with taxonomies. Raymond Hettinger, Python core developer: Put the Dog on top, if the Dog has more code that is useful for Animal From The art of subclassing, Raymond Hettinger. "How do you decide which one is on top? There is no principle of specialization. (...) Why do we subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.” http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
  • 16. as object oriented languages (VI) polymorphism [1] - ad-hoc polymorphism: function overloading [already covered] - parametric polymorphism: generic type that can handle different types without worrying about their types. Java: generics: List<String> l = new ArrayList<String>(); Python: builtin: l = [] [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 17. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Java: inheritance + interfaces + static typing public class Duck extends Bird implements Swimmer{ public String quack(){ (...) public void walk(){ (...) (...) Duck donald = new Duck(); donald.walk(); donald.fly(); donald.quack(); donald.swim(); [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 18. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Python: inheritance + duck typing + protocols class Duck(Bird): def quack(): def walk(): (...) (...) (...) donald = Duck() donald.walk() donald.fly() donald.quack() donald.swim() [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 19. as object oriented languages (VII) encapsulation: OCP (open closed principle) : "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification" http://en.wikipedia.org/wiki/Open/closed_principle visibility (public, protected, ...), javabeans (Java) versus "_", "we are all consenting adults here" (Python) [1] Python name mangling. [1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932. html
  • 20. execution model (I) Python execution model differs from those of Java and C++. In Python everything is a name bounded to an object. In Java class lifecycle is separated in load, initialization and execution. In Python, LoC are executed. No separation between declaration and execution. 1. Class resolved and loaded. 2. Class is initialized. 3. Code in class used. Functions (def) (class) Modules Entry points to code well defined: main Classes (import) Entry points to code are the same modules
  • 21. execution model (III) ● Diferenciate explicit execution from import time execution? if __name__ == ‘_main__’: “””your program here”””
  • 22. execution model (III) ● ● ● implicit variable declaration duplicate declarations parameter default values that are mutable class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [5]: a = A(p2=3) In [6]: a.method1(1, 2) 1 In [9]: print a.lastp1 1 In [10]: a2 = A(p1=3) In [12]: print a2.v3 [2] In [13]: print a.v3 [2]
  • 23. execution model (IV) monkey patching class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [22]: a = A() In [23]: a.method1(1, 2) 1 In [24]: def m1(self, p, p2): print 'modified ' + str (p) ....: In [25]: A.method1 = m1 In [26]: a.method1(1, 2) modified 1 Remember: in Python everything is a name bounded to an object.
  • 24. wrap up You solve the problems. The most important part of any language is you, the developer. No clear winner, today I prefer Python. Thanks for attending!