Is my thinking Pythonic?

Diez B. Roggisch deets at nospam.web.de
Thu Aug 21 08:36:17 EDT 2008


Hussein B wrote:

> Hey,
> Well, as you all know by now, I'm learning Python :)
> One thing that is annoying my is the OOP in Python.
> 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:
>   def setspeed(self, speed):
>      self.speed = speed
>   def setbrand(self, brand):
>      self.brand = brand
> --
> If you have a huge class, you can't figure the instance variables of
> each object.
> So, I created this constructor:
> --
> def __init__(self):
>   self.speed = None
>   self.brand = None
> --
> 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?
> Any suggestions?

The approach is exactly right - instance variable should be (don't have to,
though) declared inside the __init__-method.

However, you *are* unpythonic in defining getters and setters. These are a
java-atrocity that mainly exists because java has no concept of properties
or delegates, and thus can't add code to instance variable assignments.
Thus one needs to wrap *all* variables into get/set-pairs, such that in the
case of a behavior-change (e.g. lazyfying) one does not need to change
client-code.

Maybe this reading will help you adjust your mindset:

http://dirtsimple.org/2004/12/python-is-not-java.html


Diez



More information about the Python-list mailing list