A Suggestion for Python Dictionary/Class

William Djaja Tjokroaminata billtj at y.glue.umd.edu
Fri Dec 22 22:00:57 CET 2000


Hi all,

After using Python for a while, a have a wish for another type of
dictionary.  If you ever used Tcl and Perl, you know that all Python, Tcl,
and Perl basically provides three different fundamental data types:

    - scalar (Perl-speak) (which includes numbers and strings)
    - list (or sequence in Python-speak)
    - dictionary

But in Python, we have two different kinds of lists: lists and tuples.  I
used Tcl and Perl before, so initially I was puzzled by why Python
provides a 'read-only' list.  But it is fine.

I also use C and C++ a lot.  Their power and large-scale capabilities come
from, among other things, the ability to write struct or class.  Among the
three scripting languages, only Python provides the most natural form of
struct/class like in C/C++/Java.  That's why I love Python so much; I can
think in Python much like I think in C/C++/Java.

However, there is a fundamental difference with Python class.  The members
are implemented using dictionary.  The danger with dictionary is, even
though a key does not exist, we still can make an assignment to it.  When
we make some typo, this can be hard to debug.  For example:

    class MyClass:
        def __init__ (self):
            self.member = 0

    myClass = MyClass ()
    myClass.menber = 1    # This is a bug!

    print myClass.member  # Expected 0, but found 1

In C/C++/Java, if a member does not exist and we try to access or assign
it (because of some typo, perhaps), it will be caught by the compiler
simply as syntax error.  Not so with Python class.

Therefore, is there any way for me to define a class, with some definite
members just like in C/C++/Java, so that no new members can be defined?  I
am trying to do it, but using some conventions, not using the Python
language features.

Because Python provides a read-only list in terms of tuple, I think it
will be nice if Python provides another class type with fixed members,
just like a dictionary with read-only keys.  Any opinion, anyone?

Regards,

Bill



More information about the Python-list mailing list