How do these Java concepts translate to Python?
Ben Finney
bignose+hates-spam at benfinney.id.au
Fri Aug 12 01:23:07 EDT 2005
Ray <ray_usenet at yahoo.com> wrote:
> 1. Where are the access specifiers? (public, protected, private)
No such thing (or, if you like, everything is "private" by default).
By convention, "please don't access this name externally" is indicated
by using the name '_foo' instead of 'foo'; similar to a "protected".
Nothing in the language enforces this.
Recently, the language came to partially support '__foo' (i.e. a name
beginning with two underscores) as a pseudo-"private". It's just a
namespace munging though; sufficiently determined users can get at it
without much effort.
The attitude engendering this simplicity is "we're all consenting
adults here". If you have users of your modules and classes who won't
respect access restriction *conventions*, they're bad programmers
anyway, so there's not much the language can do to stop that.
> 2. How does Python know whether a class is new style or old style?
> E.g.:
>
> class A:
> pass
New-style classes are descended from class 'object'. Old-style classes
aren't.
Thus, your example above is an old-style class, as are any classes
that inherit only from that class.
To create a new-style class with no particular base functionality,
inherit from 'object' directly:
class A(object):
pass
> 3. In Java we have static (class) method and instance members. But
> this difference seems to blur in Python.
Class attributes and instance attributes are distinguished by the fact
that instance attributes are created when the instance is created
(typically, assigned within the __init__() method):
class A(object):
foo = 'Fudge'
def __init__(self, bar):
self.bar = bar
wibble = A('Wibble')
print wibble.foo, wibble.bar # Fudge Wibble
bobble = A('Bobble')
print bobble.foo, bobble.bar # Fudge Bobble
Instances of the 'A' class all share a 'foo' attribute, and each
instance has its own 'bar' attribute created separately (in the
__init__() method).
--
\ "Unix is an operating system, OS/2 is half an operating system, |
`\ Windows is a shell, and DOS is a boot partition virus." -- |
_o__) Peter H. Coffin |
Ben Finney <http://www.benfinney.id.au/>
More information about the Python-list
mailing list