Hussein B a écrit :
Hey,
Well, as you all know by now, I'm learning Python :)
One thing that is annoying my is the OOP in Python.

If so, the answer to your question is "obviously, no" !-)

Ok, let's see...

Consider this code in Java:
--
public class Car {
  private int speed;
  private String brand;
  // setters & getters
}
--
With one look at the top of the class, you  can know that each
instance has two instance variables (speed & brand).
I tried to transform in into Python:
--
class Car:

Unless you have a compelling reason, use new-style classes:

class Car(object)

  def setspeed(self, speed):
     self.speed = speed
  def setbrand(self, brand):
     self.brand = brand

Java, C++ etc require getters and setters because they have no support for computed attributes, so you cannot turn a plain attribute into a computed one without breaking code. Python has good support for computed attributes, so you just don't need these getters and setters. The pythonic translation would be:

class Car(object):
    def __init__(self, speed, brand):
        self.speed = speed
        self.brand = brand

If you have a huge class, you can't figure the instance variables of
each object.

If your class is that huge, then it's probably time to either refactor and/or rethink your design.

So, I created this constructor:

<mode="pedantic">
s/constructor/initialiser/
</mode>


--
def __init__(self):
  self.speed = None
  self.brand = None

If I may ask : why don't you pass speed and brand as parameters ? If you want to allow a call without params, you can always use default values, ie:

class Car(object):
    def __init__(self, speed=None, brand=None):
        self.speed = speed
        self.brand = brand


This way, I can figure the instance variables by just reading the
__init__ method.
What do you think of my approach? is it considered Pythonic?

As far as I'm concerned - and modulo the question about initiliser's params - I consider good style to set all instance attributes to sensible default values in the initializer whenever possible, so, as you say, you don't have to browse the whole code to know what's available.

Now remember that Python objects (well, most of them at least) are dynamic, so attributes can be added outside the class statement body.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to