Idea about method parameters
Markus Schaber
markus at schabi.de
Wed Sep 26 11:23:06 EDT 2001
Hi,
Toby Dickenson <tdickenson at devmail.geminidataloggers.co.uk> schrub:
> I assume you would not want to allow:
>
> class A:
> def __init__(self, some_other_object.value):
> pass
>
> But the distinction between the two is unexpected.
The distinction that I can only use names of the local procedure scope
and not every accessible name is also somehow "unexpected", at least
inconsistent. (This is how it is now and in all other languages I know)
> There is a way to shorten a __init__ with many parameters within the
> current language, without sacrificing readability. Shorter, but also
> wider.....
>
> class A:
> def __init__(self, value1, value2, value3):
> self.value1,self.value2,self.value3 = value1,value2,value3
>
>
> (my appologies if you already knew of this)
Yes, I know this, and it is not really much shorter. And I would not
call it more readable than three assignments on three lines on their
own. Imagine you have 10 values, and you have to count by hands if you
want to change one of them.
Then I would prefer
self.value1=value1; self.value2=value2; self.value3=value3
And it is slightly slower, i ran the following Test:
import time
def test(obj):
start = time.clock()
for i in xrange(100000):
obj.test(1,2,3,4,5,6)
stend = time.clock()
print obj.descr,round(stend-start,3)
class Direct:
descr="One per line: "
def test(self, a, b, c, d, e, f):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
class Tupel:
descr="Using Tuples: "
def test(self, a, b, c, d, e, f):
self.a,self.b,self.c,self.d,self.e,self.f = a,b,c,d,e,f
class Concatenated:
descr="All on one line: "
def test(self, a, b, c, d, e, f):
self.a = a;self.b = b;self.c = c;self.d = d;self.e = e;self.f = f
D = Direct()
T = Tupel()
C = Concatenated()
test(D)
test(T)
test(C)
test(D)
test(T)
test(C)
My results using Python 1.5.2 and Python 2.0.1:
schabi at lunix:~/python/test$ python assignment.py
One per line: 1.36
Using Tuples: 1.44
All on one line: 1.34
One per line: 1.4
Using Tuples: 1.57
All on one line: 1.33
schabi at lunix:~/python/test$ python2 assignment.py
One per line: 1.42
Using Tuples: 1.55
All on one line: 1.42
One per line: 1.44
Using Tuples: 1.55
All on one line: 1.38
This shows that the ;-approach is the fastest (because of the lack of
the linenumber increasing bytecode instructions, I guess), and your is
the slowest (because of the tupel packint/unpacking I guess).
markus
--
"The strength of the Constitution lies entirely in the determination of
each citizen to defend it. Only if every single citizen feels duty
bound to do his share in this defense are the constitutional rights
secure." -- Albert Einstein
More information about the Python-list
mailing list