How do these Java concepts translate to Python?

bruno modulix onurb at xiludom.gro
Fri Aug 12 04:51:37 EDT 2005


Ray wrote:
> Hello,
> 
> I've been learning Python in my sparetime. I'm a Java/C++ programmer by
> trade. So I've been reading about Python OO, and I have a few questions
> that I haven't found the answers for :)
> 
> 1. Where are the access specifiers? (public, protected, private)

object.name => public
object._name => protected
object.__name => private

> 2. How does Python know whether a class is new style or old style?
> E.g.:
> 
> class A:
>     pass

This is an old-style class.

> How does it know whether the class is new style or old style? Or this
> decision only happens when I've added something that belongs to new
> style? How do I tell Python which one I want to use?

class B(object): # or any subclass of object
  pass

> 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? 

Depends if you bind it to the class or to the instance !-)

> It seems that everything
> is static (in the Java sense) in Python. Am I correct?

No.

class Foo(object):
  bar = 42 # this is a class variable

  # __init__ is the equivalent of Java constructors
  def __init__(self, baaz):
    self.baaz = baaz # this is an instance variable

  # this is a class method
  # (the first argument is the class object, not the instance)
  @classmethod
  def bak(cls, frooz):
    cls.bar = min(cls.bar, frooz) + 1138

  # default is instance method
  def zoor(self):
    print "%s %d" % (self.baaz, Foo.bar)

> Thanks in advance,

HTH



-- 
bruno desthuilliers
ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list