On Tue, 27 Feb 2007 20:59:03 +0000, Alan Isaac wrote:

> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> class Difficult(object):
>     def __setattr__(self, name, value):
>         if self.__dict__.has_key(name):
>             print "'%s' exists as an instance attribute" % name
>             self.__dict__[name] = value
>         elif self.__class__.__dict__.has_key(name):
>             print "'%s' exists as a class attribute" % name
>             self.__class__.__dict__[name] = value
>         else:
>             print "Can't create new attributes, 'cos I said so!"
> 
> 
> 
> But this prevents setting attributes during initialization,
> so it does not meet the spec.

What, you expect us to do everything for you? *wink*

If you want the class to change behaviour after initialisation, you have
to code it to do so. The easy, but inelegant, way is to set a flag.

Finding an elegant way to do so is a little like asking for an elegant way
to scrub a septic tank clean. But one way might be to change the class
after initialisation:

class Parrot(object):
    def __init__(self, data):
        self.data = data
        self.__class__ = Annoying

class Annoying(Parrot):
    def __setattr__(self, name, value):
        print "Annoy the user."

>>> x = Parrot(5)
>>> x.data
5
>>> x.data = 7
Annoy the user.
>>> x.data
5


-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to