identifier class enforcement

Jeff Epler jepler at unpythonic.net
Tue Jul 20 01:42:15 CEST 2004


I'd write Identifier as a function:
    def Identifier(s):
        return s.strip().replace(" ", "_")
unless it's important that Identifier be a class.  If it is, use a str
subclass and the __new__ method as suggested by another poster.

In Class, I'd use a property to call a setter function when name is
modified:
    class Class(object): #subclass of object required for property to work
        def set_name(self, newname):
            self.__name = Identifier(newname)
        def get_name(self):
            return self.__name
        name = property(get, set)

        def __init__(self, name):
            self.name = name

The setting of self.name in __init__ or anywhere else in the program
will go through the setter function, set_name, enforcing the requirement
that the name be an Identifier.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040719/a9d8eca7/attachment.pgp>


More information about the Python-list mailing list