Data attributes...

Joseph A Knapka jknapka at earthlink.net
Thu Jan 24 13:22:03 EST 2002


Lawrence Oluyede wrote:
> 
> I've just read about data attributes.
> 
> The tut says:
> 
> "Data attributes need not be declared; like local variables, they
> spring into existence when they are first assigned to"
> 
> Why that? I think it could be illegal...

But it *is* legal, as your example demonstrates.

> see the ex:
> 
> class MyClass:
>     "A simple example class"
>     i = 12345
> 
>     def f(self):
>         return 'hello world'
> 
> x = MyClass()
> 
> x.counter = 1
> while x.counter < 10:
>     x.counter = x.counter * 2
> print x.counter
> del x.counter
> 
> it prints 16
> 
> but the question is...why??

This is just the nature of Python. This kind of flexibility
can be extremely convenient, and the more you use Python, the
more you'll appreciate it. For example, I have an application
that parses a file and produces a syntax tree made up of
objects of class SyntaxNode. Later I wanted to be able to
graphically display the syntax tree. In C++, I would have
had to either diddle the SyntaxNode class to add GUI data
that the parser would never use, or else create a new
class for GUISyntaxNodes that either derived from SyntaxNode
and added the appropriate data, or else kept a reference to
the associated SyntaxNode, and copy the entire SyntaxNode tree
into a tree of GUISyntaxNodes for the UI's benefit. But in Python,
the UI code just takes the syntax tree from the parser, marks
it up by assigning the data it requires to the existing
SyntaxNode objects, and displays the tree. Easy as pie.
With the parser in place, it took me only about an hour
to write the display code, and that code is reasonably clear
and easy to maintain. Of course, this means that the
parser and the UI are more tightly coupled than they would
be if I had taken a more traditional approach, but the
point is, it was *easy*, and it *works*. If ever I need
to pull the parser and UI completely apart and work with
them independently, I can do the necessary abstraction in
a short time.

> With this feature i could make my sources
> hard to read and so confused i think...

As the sage said, "Don't do that." :-) It's very easy to
refactor Python code (much, much easier than, say, Java
or C++); when the code starts to get ugly, pretty it up.

Cheers,

-- Joe
"I should like to close this book by sticking out any part of my neck
 which is not yet exposed, and making a few predictions about how the
 problem of quantum gravity will in the end be solved."
 --- Physicist Lee Smolin, "Three Roads to Quantum Gravity"



More information about the Python-list mailing list