A Suggestion for Python Dictionary/Class

Donn Cave donn at u.washington.edu
Fri Dec 22 18:27:51 EST 2000


Quoth William Djaja Tjokroaminata <billtj at y.glue.umd.edu>:
...
| 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?

When you say "using some conventions, not using the Python language
features", do you mean to reject a solution like this?

    class Fixed:
        def fixdict(self):
            for a in self.fixed_attributes:
                self.__dict__[a] = None
        def __setattr__(self, a, v):
            if self.__dict__.has_key(a):
                self.__dict__[a] = v
            else:
                raise AttributeError, a

    class Plant(Fixed):
        fixed_attributes = ('flower', 'stem', 'root', 'leaf')
        def __init__(self, n):
            self.fixdict()
            self.root = n

    p = Plant(5)
    print p.root
    print p.stem

I hope that will work for you, because it seems to provide the
behavior you describe and it works already, with no changes to
Python.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list