design question: no new attributes

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Feb 27 21:39:14 EST 2007


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

> "Steven D'Aprano" <steve at REMOVEME.cybersource.com.au> wrote in message
> news:pan.2007.02.27.07.24.57.769316 at REMOVEME.cybersource.com.au...
> 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 




More information about the Python-list mailing list