error in tutorial for 3.0, section 9.3.3
Dave Angel
davea at ieee.org
Sat May 23 12:48:05 EDT 2009
Vincent Davis wrote:
> Section 9.3.3 says that given,
> class MyClass:
> """A simple example class"""
> i = 12345
> def f(self):
> return 'hello world'
>
> and x = MyClass()
> then this
>
> x.counter = 1
> while x.counter < 10:
> x.counter = x.counter * 2
> print(x.counter)
> del x.counter
>
> will print 16
>
> link,
> http://docs.python.org/3.0/tutorial/classes.html#a-first-look-at-classes
>
> I am reading this section so to learn about classes but if this is right I
> think I need to start over.
>
>
> Thanks
> Vincent Davis
> 720-301-3003
>
>
Yes, this code will display 16, and it's not specific to 3.0, but works
in earlier Pythons as well.
I'm not sure why you're puzzled; it could be the question of why 16,
but i suspect it's because you can't see who creates this x attribute.
Unlike languages like Java and C++, object attributes are not fixed at
the time the class is compiled. Some attributes are created by the
placement of the code, for example the method name f. But others are
created in the code of the class (typically the __init__() method), and
others can be created by anyone, at any time.
I don't know why the tutorial starts with this, but it illustrates that
an object is really just a container for attributes, some of which are
callable (methods), and some of which are data (what Java would call
fields). Anybody with an object reference can create, modify or delete
those attributes. If it's being done inside the class methods, you use
the syntax self.counter. But it also works outside, as you see.
More information about the Python-list
mailing list