Adding attribute to objetcs

faulkner faulkner612 at comcast.net
Mon Jun 5 17:14:18 EDT 2006


when you set an attribute of an object, python secretly calls that
objects __setattr__ method.
class test:
    def __setattr__(self, attr_name, attr_value):
        print self, attr_name, attr_value
        self.__dict__[attr_name] = attr_value    # do what the original
__setattr__ method does.
test().fred = 'george'    # prints <test instance ...> fred george


Miguel Galves wrote:
> Hello,
>
> I`m starting to learn python, and I hava a very good background in Java
> and C/C++ programming. I was reading Dive into python chapter about
> OO and I saw that in python we can do the following:
>
> class Person:
>     pass
>
> joe = new Person()
> joe.name = "Joe"
> joe.age = 13
>
> It seems that it is possible to add attributes to any object instance
> in run time, as in Javascript. It seems to me that it can be a source
> of errors. One that come in my mind is the follwing:
>
> class Person:
>     name = ""
>
> joe = new Person()
> joe.nome = "Joe"
>
> The code above adds an attribute called nome,  but the programmer may think
> it's name.
>
> What is the real interest of this feature ? Is there a way to block this
> kind of error ?
>
> Thanks,
>
> Miguel
> --
> Miguel Galves - Engenheiro de Computação
> Já leu meus blogs hoje?
> Para geeks http://log4dev.blogspot.com
> Pra pessoas normais
> http://miguelgalves.blogspot.com
> 
> "Não sabendo que era impossível, ele foi lá e fez..."




More information about the Python-list mailing list