Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Is my thinking Pythonic?

371 views
Skip to first unread message

Hussein B

unread,
Aug 21, 2008, 8:21:23 AM8/21/08
to
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?
Thank you all.

bearoph...@lycos.com

unread,
Aug 21, 2008, 8:36:59 AM8/21/08
to
Hussein B:

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

You can also learn the _attribute and __attribute conventions.
In Python getter/setters are used less often, you can remove those two
setters and just access the attributes from outside.
Later, in derived classes, if you want to make their workings more
complex you can add properties.
Note that Python isn't able to inline things as HotSpot does, so each
getter/setter (or dot: foo.bar.baz is slower than foo.bar) you use
your code slows down.


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

Sometimes I do the same thing, to to "document" the attributes used.

Bye,
bearophile

Diez B. Roggisch

unread,
Aug 21, 2008, 8:36:17 AM8/21/08
to
Hussein B wrote:

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

Paul Boddie

unread,
Aug 21, 2008, 8:44:58 AM8/21/08
to
On 21 Aug, 14:21, Hussein B <hubaghd...@gmail.com> wrote:
> 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?

I don't like to use the term "Pythonic", but I think it's reasonable
to initialise the attributes in this way. In effect, what you're doing
is to ensure that the attributes have some well-defined state at each
point in the lifetime of the instance, and I find myself doing this a
lot. My __init__ methods typically consist of any calls to superclass
__init__ methods followed by the explicit initialisation of any
additional attributes defined for the instance in the class.

Some people might advocate not bothering defining the attributes until
they are actually set with some value, but then you have to deal with
situations where the attributes are missing. Generally, handling
missing attributes isn't worth the bother unless you have a large
number of attributes which could only *potentially* be present: a
situation which occurs when wrapping "foreign" libraries, for example,
where properties or use of __getattr__ seem more essential than the
luxury they might otherwise appear to be.

Paul

Bruno Desthuilliers

unread,
Aug 21, 2008, 11:58:54 AM8/21/08
to
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.

Craig Allen

unread,
Aug 21, 2008, 1:31:02 PM8/21/08
to
generally, I name the members in the Class definition and set them to
None there...

class Car:
speed = None
brand = None

def __init__():
self.speed = defaultspeed #alternately, and more commonly, get
this speed as a initializer argument
self.brand = defaultbrand


That solves the issue of being able to "see" all the members of an
object by reading code... however, this all goes out the window when
composing an instance dynamically (i.e. metaclass type stuff).

Diez B. Roggisch

unread,
Aug 21, 2008, 1:32:58 PM8/21/08
to
Craig Allen wrote:

While I use this idiom myself, one must be cautious not to create unwanted
side-effects if anything mutable comes into play:

class Foo:
bar = []

def baz(self):
self.bar.append(2)


will *not* make bar instance-variable, but keep it as class-variable.

bearoph...@lycos.com

unread,
Aug 21, 2008, 1:40:29 PM8/21/08
to
Craig Allen:

> class Car:
> speed = None
> brand = None
>
> def __init__():
> self.speed = defaultspeed #alternately, and more commonly, get
> this speed as a initializer argument
> self.brand = defaultbrand
>
> That solves the issue of being able to "see" all the members of an
> object by reading code... however, this all goes out the window when
> composing an instance dynamically (i.e. metaclass type stuff).

I think that's better to avoid class attributes if you don't need
them, then shade them with object attributes with the same name, etc,
it looks like a way to make things messy...

Bye,
bearophile

Gabriel Genellina

unread,
Aug 21, 2008, 2:34:52 PM8/21/08
to pytho...@python.org
En Thu, 21 Aug 2008 14:31:02 -0300, Craig Allen <call...@gmail.com>
escribi�:

> generally, I name the members in the Class definition and set them to
> None there...
>
> class Car:
> speed = None
> brand = None
>
> def __init__():
> self.speed = defaultspeed #alternately, and more commonly, get
> this speed as a initializer argument
> self.brand = defaultbrand

This isn't a good idea as discussed in this recent thread
http://groups.google.com/group/comp.lang.python/browse_thread/thread/b4001042e59bcc29/

--
Gabriel Genellina

Bruno Desthuilliers

unread,
Aug 21, 2008, 4:34:22 PM8/21/08
to
Craig Allen a écrit :

> generally, I name the members in the Class definition and set them to
> None there...
>
> class Car:

Unless you have a really good reason to use an antiquated and deprecated
object model, use "new-style" classes (for a value of "new" being "now
many years old"):

class Car(object):

> speed = None
> brand = None
>
> def __init__():
> self.speed = defaultspeed #alternately, and more commonly, get
> this speed as a initializer argument
> self.brand = defaultbrand
>

Please dont. This is a useless repetition, a violation of the DRY
principle, and a potential waste of time for the maintainer who will
wonder what these class attributes are for.

> That solves the issue of being able to "see" all the members of an
> object by reading code...

Not even.

> however, this all goes out the window when
> composing an instance dynamically (i.e. metaclass type stuff).

No need for metaclasses here. Instances are *always* composed
dynamically. While I agree that setting all attributes to a sensible
default in the initializer is *usually* good style (even if it's
technically useless and possibly error prone), duplicating them all as
class attribute is at best a WTF (IMHO and all other disclaimers here...).

Fredrik Lundh

unread,
Aug 22, 2008, 3:52:48 AM8/22/08
to pytho...@python.org
Bruno Desthuilliers wrote:

> Unless you have a really good reason to use an antiquated and deprecated
> object model, use "new-style" classes (for a value of "new" being "now
> many years old"):

the distinction is gone in 3.0, so can we please stop flaming people for
violating a crap rule that's quite often pointless in 2.X and completely
pointless in 3.0?

</F>

Bruno Desthuilliers

unread,
Aug 22, 2008, 5:20:53 AM8/22/08
to
Fredrik Lundh a écrit :

> Bruno Desthuilliers wrote:
>
>> Unless you have a really good reason to use an antiquated and
>> deprecated object model, use "new-style" classes (for a value of "new"
>> being "now many years old"):
>
> the distinction is gone in 3.0,

Yeps, but not in 2.5.2, which is still the current stable release.

> so can we please stop flaming people

Hear hear... Now *this* is a very sound advice.

> for
> violating a crap rule that's quite often pointless in 2.X and completely
> pointless in 3.0?

Given the lack of proper support for the descriptor protocol in
old-style classes and a couple other diverging behaviors, I wouldn't say
that advising newcomers to use new-style classes is so pointless.

Fredrik Lundh

unread,
Aug 23, 2008, 6:15:06 AM8/23/08
to pytho...@python.org
Bruno Desthuilliers wrote:

> Given the lack of proper support for the descriptor protocol in
> old-style classes and a couple other diverging behaviors, I wouldn't say
> that advising newcomers to use new-style classes is so pointless.

Yeah, but if you don't need descriptors, new-style classes don't buy you
anything (except a slight slowdown in certain situations). Dogmatic use
of new-style classes (or any other "new" feature) isn't "pythonic".

</F>

Bruno Desthuilliers

unread,
Aug 26, 2008, 6:29:41 AM8/26/08
to
Fredrik Lundh a écrit :

> Bruno Desthuilliers wrote:
>
>> Given the lack of proper support for the descriptor protocol in
>> old-style classes and a couple other diverging behaviors, I wouldn't
>> say that advising newcomers to use new-style classes is so pointless.
>
> Yeah, but if you don't need descriptors, new-style classes don't buy you
> anything

Except being python-3000 ready wrt/ diverging behavious - like
overriding __magic__ methods on a per-instance basis. Ok, this is
certainly not a very common case, but still we've seen questions about
this on this ng...

> (except a slight slowdown in certain situations).
> Dogmatic

"dogmatic" ???

> use
> of new-style classes (or any other "new" feature) isn't "pythonic".

You're right to quote the word "new" here - how many years since Python
grew a new object model explicitely intended to replace the original one ?

0 new messages