Encapsulation, inheritance and polymorphism

Terry Reedy tjreedy at udel.edu
Tue Jul 17 13:07:38 EDT 2012


On 7/17/2012 10:23 AM, Lipska the Kat wrote:

> Well 'type-bondage' is a strange way of thinking about compile time type
> checking and making code easier to read (and therefor debug

'type-bondage' is the requirement to restrict function inputs and output 
to one declared type, where the type declaration mechanisms are usually 
quite limited.

 >>> def max(a, b):
	if a <= b: return a
	return b

 >>> max(1,3)
1
 >>> max(3.3, 3.1)
3.1
 >>> max('ab', 'aa')
'aa'
 >>> max([1,1], [1,0])
[1, 0]

and so on, indefinitely. How easy is it to write the same in Java?
Similarly, list.sort sorts any list as long as a < b works for all pairs 
of items in the list.

Function max works for any two objects as long as 'a <= b' works. So the 
'type' of a and b is 'mutually comparable with <='.  How do you declare 
that in Java? How do you declare the type 'non-negative number'? In 
python, putting 'if input >= 0:' as the top effectively 'declares' that 
input must be a number and greater than 0.

> but I'm not about to get into some religious war about declaring a variables
> type.

In Python, *all* data items have a class (type). Names in code do not 
have a type. When they become data items, they are strings. 'Variable' 
is a somewhat fuzzy term or concept in Python.

Since every object is an instance of some class, every class is a 
subclass of class 'object', and an instance of a class is an instance of 
all its classess superclasses; every object is an instance of 'object'. 
So 'object' is the type of all inputs until further restricted. id(ob) 
produces an integer for all objects. str(ob) is intented to produce a 
string representation for all objects. The print functions calls str on 
all its inputs.

> I'll just say that I prefer to devote testing efforts to the real
> danger area which in my experience is 'user' input.
> Clients look dimly on runtime errors however they occur and if I can
> leave it to the compiler to check as much as possible then I'll take that.

import ast
a = ast.literal_eval(input('enter a value: '))
b = ast.literal_eval(input('enter a comparable value: ')
try:
     print('the max of those two is ', max(a,b))
except TypeError:
     print(a, ' and ', b, ' are not comparable')

I suppose

> Still, I'm sure you're only kidding around with me :-)

How easy was it to write max, or a universal sort in Java?

-- 
Terry Jan Reedy






More information about the Python-list mailing list