473,787 Members | 2,971 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is my thinking Pythonic?

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.
Aug 21 '08 #1
11 1395
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
Aug 21 '08 #2
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
Aug 21 '08 #3
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.
Aug 21 '08 #4
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).
Aug 21 '08 #5
Craig Allen wrote:
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).
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.
Aug 21 '08 #6
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
Aug 21 '08 #7
En Thu, 21 Aug 2008 14:31:02 -0300, Craig Allen <ca*******@gmai l.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....01042e59bcc29/

--
Gabriel Genellina

Aug 21 '08 #8
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>

Aug 22 '08 #9
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.
Aug 22 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
13274
by: Tom Evans | last post by:
My basic question: If I have a specific interface which I know is going to be implemented by a number of classes, but there is no implementation commonality between them, what is the preferred form for this in Python? In a staticly typed language like c++ or java, I'd describe the interface first, then create the classes eithered derived from that ABC or implementing that interface (same thing really). This was the first thing I...
1
1471
by: asdf sdf | last post by:
i need some advice. i'm a back end programmer historically, but have been exploring python for webapps and enjoying it. i need to build some simple Win client-server or standalone apps. the result needs to look professional and attractive, and i need something i can get working fairly quickly with a modest learning curve. i'm looking at wxPython, because that is a pythonic solution. but i'm concerned about the scarcity of gentle...
12
1535
by: Nickolay Kolev | last post by:
Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is calculated as the sum of the transition scores between the characters in that string. The transition scores are stored in a 26 x 26 matrix. I.e. the transition A -> F would have the score soundScoreMatrix.
15
2289
by: Ville Vainio | last post by:
Pythonic Nirvana - towards a true Object Oriented Environment ============================================================= IPython (by Francois Pinard) recently (next release - changes are still in CVS) got the basic abilities of a system shell (like bash). Actually, using it as a shell is rather comfortable. This all made me think... Why do we write simple scripts to do simple things? Why do we serialize data to flat text files in...
10
5847
by: Bulba! | last post by:
Hello everyone, I'm reading the rows from a CSV file. csv.DictReader puts those rows into dictionaries. The actual files contain old and new translations of software strings. The dictionary containing the row data looks like this: o={'TermID':'4', 'English':'System Administration', 'Polish':'Zarzadzanie systemem'}
11
5050
by: Charles Krug | last post by:
I've a function that needs to maintain an ordered sequence between calls. In C or C++, I'd declare the pointer (or collection object) static at the function scope. What's the Pythonic way to do this? Is there a better solution than putting the sequence at module scope?
4
1800
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design software in a more "Pythonic" way. My question is, should we as python developers be trying to write code that follows more of a python standard or should we try to spend our efforts to stick to a more traditional OO model? For example, in...
3
1314
by: jnair | last post by:
My Tead Lead my object counter code seen below is not pythonic class E(object): _count = 0 def __init__(self): E._count += 1 count = property(lambda self: E._count ) def test(): if __name__ == "__main__":
26
1862
by: Frank Samuelson | last post by:
I love Python, and it is one of my 2 favorite languages. I would suggest that Python steal some aspects of the S language. ------------------------------------------------------- 1. Currently in Python def foo(x,y): ... assigns the name foo to a function object. Is this pythonic? Why not use the = operator like most other assignments?
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10169
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.