Emulating C++ coding style

Donn Cave donn at u.washington.edu
Mon Apr 26 12:40:25 EDT 1999


Martijn Faassen <faassen at pop.vet.uu.nl> writes:
| Donn Cave wrote:
...
|> It's not much like C++ here, but it's uncanny how it reeks of Python!
|> Namespaces, references!
|
| Indeed. Not having used that class attribute trick often myself, I
| wasn't aware of this surprising behavior. I suppose in order to get the
| C++ behavior it's best to use a module global variable.

Not at all, either way is fine - the class scope is just as good a place
as the module scope, for me it's the perfect place for things that are
specific to the class.

It's the usage that you have to watch out for, and while there are some
perils for the unwary, in the long run it's also an opportunity to gain
a deeper understanding of how simple Python is.  Same for module attributes -
common problem, someone imports a module attribute like

   from foo import shared
   shared = 5

and then wonders, how come no change to the attribute as seen from other
modules.  The right way to set to a module attribute - if you must do this
at all - is

   foo.shared = 5

and just the same for a class attribute (of class Foo):

   from foo import Foo
   Foo.shared = 5

In general, you have the problem only when your usage doesn't reflect the
design.  If it's really a class attribute, but you set it in the instance
scope, if it's really an external module attribute but you bind it into
the present module's scope during import.  Python bites if you trick it.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list