[Tutor] classes : post-declaration attributes
Mitya Sirenef
msirenef at lightbird.net
Sat Feb 9 08:22:33 CET 2013
On 02/09/2013 02:01 AM, neubyr wrote:
>
> I am learning Python 2.7 classes and objects. It seems like
attributes (data attributes and methods) can be added to a class/object
even after it's first declaration. For example,
>
> <code>
> class A(object):
> def __init__(self,arg):
> self.val1 = arg
>
> a = A(1)
> print a.val1
> </code>
>
> Now another data attribute val2 can be added as:
> <code>
> a.val2 = 2
> A.val2 = 22
> </code>
>
> 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
>
> --
> thanks,
> N
>
What is meant there is that without any additional assignments, those
attributes will be valid, I think.
You can assign attributes at a later time if they don't exist at the
time class is defined, or even if it's just more convenient for your
needs. E.g. you can simply store some values in instance attributes at
various points in your program.
-m
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
Fanaticism consists of redoubling your effort when you have forgotten your
aim. George Santayana
More information about the Tutor
mailing list