[Tutor] Class definition confusion

Alan Gauld alan.gauld at btinternet.com
Wed Feb 15 19:33:10 CET 2012

On 15/02/12 18:14, Sivaram Neelakantan wrote:
> I was under the impression that you have to define the attributes of
> the class before using it in an instance.

Only in some languages. Python is not one of those.

>>>> class Point:
> ...     """pts in 2d space"""
> ...
>>>> b = Point()
>>>> b.x =3
>>>> b.y =4
>>>> print b.y
> 4
> Why is it not throwing an error?  This is confusing me a bit.

Python allows instance attributes to be added at runtime.
In general this is a bad idea IMHO, a dictionary would probably
be more appropriate, but there can, very occasionally, be valid
uses for it.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list