[Tutor] When to use a Class or just define functions?
Magnus Lyckå
magnus@thinkware.se
Fri Jun 20 19:05:01 2003
At 15:40 2003-06-20 -0600, Bob Gailer wrote:
>Oh I disagree. A class can do what a C struct does; collect properties
>that have potentially differing values for various instances, and no methods.
But a blank class like that is more like a namespace
than it is like a struct. A C struct has a defined
structure--it provides space for certain types of
data, but an empty class is more like a restricted
dict where the keys have to be strings that fulfill
the requirements of identifiers, and the syntax for
using it is different.
Something more similar to a C struct would be a new
style class with slots. See
http://www.python.org/2.2.3/descrintro.html
E.g.
>>> class PersonStruct(object):
... __slots__ = ['fname', 'lname', 'id']
...
>>> p = PersonStruct()
>>> p.fname = 'Guido'
>>> p.lname = 'van Rossum'
>>> p.id = 1
>>> p.email = 'guido@example.com'
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'PersonStruct' object has no attribute 'email'
Of course, this construct will allow any type in any
attribute. To make it type checked like C, you need to
use properties or something like that, which is also
described in descrintro.html...
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language