__init__, __slot__ and **keywordargs

Zunbeltz Izaola zunbeltz at wm.lc.ehu.es.XXX
Fri Jan 9 08:41:29 CET 2004


Hi,

I'm playing with __slot__ (new class) and the __init__ method of my
class. I want the arguments of __init__ to be keywords and that the
method initialize all the attributes in __slot__ to None except those
in the argument of __init__ (Is this a good practice?). I've the
following class

class PersonalData(object):

    __slot__ = ("Firstname",    # Firstname of the person.
                "Surname",      # Surname of the person.
                "Birthdate",    # Birthdate of the person.
                "Nationality"   # Nationality of the person.
                )

    def __init__(self,**args):
        for kwrd, value in args.items():
                self.__setattr__(kwrd,args[kwrd]

#        for arg,value in args.items():
#            if arg in self.__slot__:
#                self.__setattr__(arg,value)
#            else:
#                errmsg = str(self.__class__.__name__)
#                errmsg += "object has not attribute " + arg 
#                raise AttributeError, errmsg

    def __str__(self):
        buffer = ""
        for attr in self.__slot__:
            if attr in self.__dict__.keys():
                buffer += attr + ": " + str(self.__getattribute__(attr)) + "\n"

The problem is that the __init__ defined can set attributes that are
not in the slot and i want to have an exception when someone tries to
do

inst = PersonalData(noattribute = "Smith")

I've coded the solution in the fragment that is commented, raising and
exception manually. Someone knows a more elegant solution and can
explain with the first definition didn't raise and exception?

Thanks in advance 

Zunbeltz
-- 
Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX



More information about the Python-list mailing list