[Tutor] Class definition confusion
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Feb 15 19:43:53 CET 2012
On 15/02/2012 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. Following the book
> 'thinking in Python',
>
>>>> class Point:
> ... """pts in 2d space"""
> ...
>>>> print Point
> __main__.Point
>>>> 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.
>
> sivaram
> --
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
Your impression is incorrect. This type of behaviour is allowed because
of Python's dynamic nature, so the following is fine.
>>> class Point:
... """pts in 2d space"""
...
>>> b = Point()
>>> b.x = 3
>>> b.y = 4
>>> del b.x
>>> del b.y
>>> b.l = 5
>>> b.m = 6
>>> print b, b.l, b.m
<__main__.Point instance at 0x02FB89B8> 5 6
Also be careful of your terminology. Here we are discussing instance
attributes. Class attributes are different in that they are are shared
at the class level so.
>>> class Point:
... """pts in 2d space"""
... x = 3
... y = 4
...
>>> a = Point()
>>> b = Point()
>>> a.x
3
>>> b.y
4
HTH.
--
Cheers.
Mark Lawrence.
More information about the Tutor
mailing list