53 lines
1.9 KiB
Plaintext
53 lines
1.9 KiB
Plaintext
|
From: donn at u.washington.edu (Donn Cave)
|
||
|
Date: 26 Apr 1999 16:40:25 GMT
|
||
|
Subject: Emulating C++ coding style
|
||
|
References: <371F8FB7.92CE674F@pk.highway.ne.jp> <371F9D0C.4F1205BB@pop.vet.uu.nl> <7foe7r$15mi$1@nntp6.u.washington.edu> <37245184.3AADF34D@pop.vet.uu.nl>
|
||
|
Message-ID: <7g24tp$raa$1@nntp6.u.washington.edu>
|
||
|
Content-Length: 1536
|
||
|
X-UID: 22
|
||
|
|
||
|
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
|
||
|
|
||
|
|
||
|
|
||
|
|