How do these Java concepts translate to Python?
Steven Bethard
steven.bethard at gmail.com
Fri Aug 12 00:36:07 EDT 2005
Ray wrote:
> 1. Where are the access specifiers? (public, protected, private)
There's no enforceable way of doing these. The convention is that names
that begin with a single underscore are private to the
class/module/function/etc. Hence why sys._getframe() is considered a
hack -- it's not officially part of the sys module.
> 2. How does Python know whether a class is new style or old style?
> E.g.:
>
> class A:
> pass
That's an old-style class. All new-style classes inherit from object
(or another new-style class). So write it like:
class A(object):
pass
If you're just learning Python now, there's really no reason to use
old-style classes. They're only there for backwards compatibility.
> 3. In Java we have static (class) method and instance members. But this
> difference seems to blur in Python. I mean, when you bind a member
> variable in Python, is it static, or instance? It seems that everything
> is static (in the Java sense) in Python. Am I correct?
No, there's a difference, but things can get a little tricky. We'll
start with the easy one:
py> class A(object):
... x = 0 # "static", class-level
... def __init__(self):
... self.y = 1 # "non-static", instance-level
...
The difference between a "static", class-level attribute and a
"non-static", instance-level attribute is whether it's set on the class
object (e.g. in the class definition), or on the instance object (e.g.
by writing self.XXX = YYY). Playing with this a bit:
py> a = A()
py> A.x # read the class-level "x"
0
py> a.x # read the *class*-level "x" (but search through the instance)
0
py> A.y # try to read a class-level "y"
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: type object 'A' has no attribute 'y'
py> a.y # read the instance-level "y"
1
Note that you can read "static" attributes from both the class and the
instance, and you can only read "non-static" attributes from the
instance, just like Java (IIRC).
Where you're likely to get confused is that instance level attributes
can shadow the class level attributes. That is, if you set an instance
attribute with the same name as a class attribute, you can't find the
class attribute through that instance anymore:
py> a.x = 2 # set the *instance*-level "x"
py> A.x # read the *unchanged* class-level "x"
0
py> a.x # read the *changed* instance-level "x"
2
HTH,
STeVe
More information about the Python-list
mailing list