instance vs class attributes

Sarir Khamsi sarir.khamsi at raytheon.com
Tue Mar 29 19:34:50 EST 2005


I come from a C++ background and am learning some of the details of
Python's OO capability and now have some questions. Given:

#!/bin/env python

class A(object):
   _x = 10
   def __init__(self): self.x = 20
   def square(self): return self.x * self.x

print 'A.x = %d' % A._x
a = A()
print 'a.x = %d' % a.x
print 'a.square() = %d' %a.square()

I get the output:

A.x = 10
a.x = 20
a.square() = 400

Here are my questions:

1) What are the benefits of using a member variable without the 'self'
   qualifier? (I think this is because you can use _x without an
   instance of A().)

2) Is there a preferred coding style (_x vs self.x)?

3) Should private data be written as self._x instead of self.x?

Thanks.

Sarir



More information about the Python-list mailing list