error in tutorial for 3.0, section 9.3.3
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
> del x.counter
> will print 16
> I am reading this section so to learn about classes but if this is right I
> think I need to start over.
> Vincent Davis
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