Emulating C++ coding style

Donn Cave donn at u.washington.edu
Thu Apr 22 20:18:03 EDT 1999


Martijn Faassen <faassen at pop.vet.uu.nl> writes:
...
|> 4. access to class's members using "::"
|>   e.g. some_class::static_value
|>   e.g. some_class::static_func(x)
|
| Python does not support static methods (or 'class methods'). Usually a
| module level global function suffices for this purpose.
|
| A static value can be created like this (besides using a global variable
| in a module):
|
| class Foo:
|    self.shared = 1
|
|    def __init__(self):
|        print self.shared

Just a nit-pick on this particular item - I tried that already, a
couple of days ago, so I know it won't work!  You meant to say,

  class Foo:
      shared = 1

Now a couple of further observations.  Per the question, yes, that
variable ("attribute") is accessible in the class scope:

   print Foo.shared

As well as in the instance scope, as shown in Martijn's example.
However, it may come as a surprise that if you assign to that attribute
in the instance scope, for example through "self" in a method, what
you get is a new reference bound in the instance scope, and other
instances still see the original class value.

   ...
   def privatize(self):
      self.shared = 0

   f1 = Foo()
   f2 = Foo()
   f1.privatize()

   print Foo.shared, f1.shared, f2.shared
   1 0 1

It's not much like C++ here, but it's uncanny how it reeks of Python!
Namespaces, references!

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




More information about the Python-list mailing list