[Tutor] classes : post-declaration attributes

Steven D'Aprano steve at pearwood.info
Sat Feb 9 08:41:53 CET 2013


On 09/02/13 18:01, neubyr wrote:

> I understand that all attributes are stored in a dictionary, but I am not
> following when adding an attribute after initial declaration approach
> should be used. The official documentation also suggests that valid
> attributes are all the names present when the class object was created [1].
> So does it mean post-declaration attributes are invalid? Why are they
> allowed to be created then (any special use cases/examples)?
>
> 1. http://docs.python.org/2/tutorial/classes.html

No, they are not invalid, merely unusual.

Normally you will create all the instance attributes you expect when you
initialise the instance:

class MyClass:
     def __init__(self, spam, ham):
         self.spam = spam
         self.ham = ham


That simply makes it easier to program the class -- you don't have to worry
about coding for the case that instance.spam doesn't exist yet, because it
will be set when the instance is created.

But sometimes you might want to add an extra, optional, attribute to an
instance after it is already initialised:

instance.eggs = 12

or delete an attribute:

del instance.ham  # No ham for you!


It's your class, you can do whatever you like to it, but it's your
responsibility if you break it.


However, note that built-in types like int, str, list etc. do *not*
allow this dynamic adding and deleting of attributes. Most builtins
don't have a __dict__, in order to be as small as possible. One of
the exceptions are functions, and I sometimes add attributes to
functions:

def spam(n):
     return "spam"*n

spam.surprise = 'NOBODY expects the Spanish Inquisition!'


Obviously that's a toy example, but I have done it in real code a
few times.


-- 
Steven


More information about the Tutor mailing list