[Tutor] a nifty python example from the python list
Sean 'Shaleh' Perry
shalehperry@home.com
Wed, 17 Oct 2001 22:30:56 -0700 (PDT)
everything below is from another poster:
I agree; you're already asking for trouble by duplicating the long list
of attribute list and in the actual parameters where Tankungen are
created, but if you create Tankungen in a lot of places, the
readability might be worth it.
Coincidentally, I wrote something this morning that might make your
life easier, and posted it under the subject 'defstruct.py'.
# I occasionally find myself writing code like the following:
# class Point:
# def __init__(self, x, y):
# self.x = x
# self.y = y
# and that's the whole class. This little module lets me write the above code
# as
# Point = defstruct('x', 'y')
# and have done with it.
#
# The name is taken from Common Lisp; the syntax is taken from MzScheme's
# define-struct and is similar to the Common Lisp boa constructor syntax.
# define-record-type from SRFI 9 is nasty and Scheme-specific enough that
# I didn't use it.
#
# I hereby dedicate this code to the public domain and disavow any copyright
# interest in it.
#
# -- Kragen Sitaker, 2001-10-16
def defstruct(*fields):
class Struct:
def __init__(self, *contents):
if len(contents) != len(self.structfields):
raise TypeError, (
"wrong number of arguments: expected %d %s, got %d" %
(len(self.structfields),
repr(self.structfields),
len(contents)))
for fieldnum in range(len(contents)):
setattr(self, self.structfields[fieldnum], contents[fieldnum])
Struct.structfields = fields
return Struct
def test():
point = defstruct('x', 'y')
p1 = point(1, 2)
assert p1.x == 1
assert p1.y == 2
complex = defstruct('real', 'imag')
assert point is not complex
assert isinstance(p1, point)
assert not isinstance(p1, complex)
test()
--
<kragen@pobox.com> Kragen Sitaker <http://www.pobox.com/~kragen/>
Perilous to all of us are the devices of an art deeper than we possess
ourselves.
-- Gandalf the White [J.R.R. Tolkien, "The Two Towers", Bk 3, Ch. XI]
--------------End of forwarded message-------------------------
We have buried the putrid corpse of Liberty. -- Benito Mussolini