Why a class when there will only be one instance?

S

SeeBelow

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since a
strength of Python is rapid application development, it slows one down
to have to put in all those self.'s. The code seems much cleaner to me
without classes that have only one instance. Oh, also, all the methods
of this class will have to have the instance name prepended to them.

I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

Mitchell Timin

--
"Many are stubborn in pursuit of the path they have chosen, few in
pursuit of the goal." - Friedrich Nietzsche

http://annevolve.sourceforge.net is what I'm into nowadays.
Humans may write to me at this address: zenguy at shaw dot ca
 
J

Jorge Godoy

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since a
strength of Python is rapid application development, it slows one down
to have to put in all those self.'s. The code seems much cleaner to me
without classes that have only one instance. Oh, also, all the methods
of this class will have to have the instance name prepended to them.

I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

How can you guarantee that such a code will never ever be used again,
anywhere?

It's easier to allow for code reuse from the beginning, IMHO.
 
S

Steve Lamb

I see the value of a class when two or more instances will be created, but
Python programmers regularly use a class when there will only be one
instance. What is the benefit of this?

What happens when down the line someone wants to use that code in
something that requires multiple instances?
 
R

Ryan Paul

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since a
strength of Python is rapid application development, it slows one down
to have to put in all those self.'s. The code seems much cleaner to me
without classes that have only one instance. Oh, also, all the methods
of this class will have to have the instance name prepended to them.

I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

Mitchell Timin

defining a class may be useful if you plan on making more instances down
the line. It's a good OO strategy. I do understand your dislike of 'self'.
It does seem like clutter. In my code, I shorten it to 's'. In ruby, class
variables are prefixed with an '@', which makes them easier to discern in
code, and it is easier than typing 'self'. I wish python had something
like that. I also think that having to specify the class variable in every
function definition is a bit silly. Ruby gets rid of that too.

--SegPhault
 
R

Roy Smith

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since a
strength of Python is rapid application development, it slows one down
to have to put in all those self.'s. The code seems much cleaner to me
without classes that have only one instance. Oh, also, all the methods
of this class will have to have the instance name prepended to them.

I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

Mitchell Timin

Typing "self" is a mechanical process which adds very little to the
development cost. Deciding which things to make classes and which not
to requires significant mental effort and does add cost. It's just
easier to make everything a class.

More than that, most times I've decided to not bother making something a
class because it was too simple, I've eventually added enough
functionality to it to change my mind and have to re-do things. That's
real cost. Much simplier and cheaper to just make it a class from the
get-go.
 
R

Roy Smith

Ryan Paul said:
defining a class may be useful if you plan on making more instances down
the line. It's a good OO strategy. I do understand your dislike of 'self'.
It does seem like clutter. In my code, I shorten it to 's'.

Please don't do that. While it's true that the first parameter of a
class method can be named anything, the use of "self" is so
overwhelmingly ubiquitous it might as well be a standard. Using
anything else is just going to make your code more difficult for anybody
else to read and understand.

Typing is cheap. Thinking is expensive. And, yes Aahz, you can quote
me on that :)
 
S

SeeBelow

Roy said:
Typing "self" is a mechanical process which adds very little to the
development cost. Deciding which things to make classes and which not
to requires significant mental effort and does add cost. It's just
easier to make everything a class.

Even easier is not to make anything a class unless there will be two or
more instances of it. I still don't get what advantage making a class
buys for you.
More than that, most times I've decided to not bother making something a
class because it was too simple, I've eventually added enough
functionality to it to change my mind and have to re-do things. That's
real cost. Much simplier and cheaper to just make it a class from the
get-go.

Why does greater functionality make a class desireable, if there won't
be multiple instances created?

Other people have mentioned "code reuse". Again I don't see how a class
helps to make code reusable. I find methods in a class more difficult
to reuse than simple function definitions. (unless there are multiple
instances.)

Mitchell Timin

--
"Many are stubborn in pursuit of the path they have chosen, few in
pursuit of the goal." - Friedrich Nietzsche

http://annevolve.sourceforge.net is what I'm into nowadays.
Humans may write to me at this address: zenguy at shaw dot ca
 
R

Roy Smith

Why does greater functionality make a class desireable, if there won't
be multiple instances created?

For me, it's more about encapsulation than code re-use. If I've got a
bunch of functions which operate on a collection of data, to me that
says "object", which in Python (and most OOPL's) implies "class".

Bundling it up into a class lets me think about it as a unit. Each
class is a convenient thought unit for design and testing, and also for
understanding somebody else's code.

I don't think there's a need to be dogmatic about it. It's just what I
find is a natural way to break a program down into smaller pieces you
can get your brain around one piece at a time.
 
S

SeeBelow

Roy said:
For me, it's more about encapsulation than code re-use. If I've got a
bunch of functions which operate on a collection of data, to me that
says "object", which in Python (and most OOPL's) implies "class".

OK, that makes some sense - to associate certain data and code items and
separate them from other code and data. Wouldn't that purpose be served
even better by putting them into a different file, and not bother with a
class?
Bundling it up into a class lets me think about it as a unit. Each
class is a convenient thought unit for design and testing, and also for
understanding somebody else's code.

I don't think there's a need to be dogmatic about it. It's just what I
find is a natural way to break a program down into smaller pieces you
can get your brain around one piece at a time.


--
"Many are stubborn in pursuit of the path they have chosen, few in
pursuit of the goal." - Friedrich Nietzsche

http://annevolve.sourceforge.net is what I'm into nowadays.
Humans may write to me at this address: zenguy at shaw dot ca
 
J

John Roth

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since a
strength of Python is rapid application development, it slows one down
to have to put in all those self.'s. The code seems much cleaner to me
without classes that have only one instance. Oh, also, all the methods
of this class will have to have the instance name prepended to them.

I'm only aware of one domain (interactive fiction) where it is really
common to have single instance classes. That's served by a number
of special purpose languages (Inform, TADS and Hugo spring to
mind). Your example (of single use classes in a UI context) seems
to be a bit contrived. I've usually found that I could get quite a bit
of code reuse out of UI classes simply by thinking the problems
through.

Granted, single use classes aren't uncommon, but instances of
other classes are much more common in most programs. In
Python, there are a number of ways of getting singletons without
very much extra effort.
I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

Both have their uses. The class / instance dicotomy comes from
the earliest days of object oriented programming, and experiments
with classless languages (see the Prothon stuff currently going on,
also the IO language) have never been very compelling. A lot of
people (which include me) think that it's much to easy to get sloppy
with that paradigm.

The other thing to understand is that in most OO languages a
class is a declaration: it does not appear in the actual object
program other than as a framework for the instances that are
created. Python is one of the few languages where classes are
first class objects.

John Roth
 
P

Peter Maas

Even easier is not to make anything a class unless there will be two or
more instances of it. I still don't get what advantage making a class
buys for you.

To use classes even in single instance cases has some advantages:

- There is a unique way of organizing your code.

- There is an easy transition to the multiple instance case.

- It makes writing meta code (e.g. for documentation, transformation
...) easier.

- Code organisation should resemble the real world problem to be modeled
(for the sake of clarity): if emphasis is on an entity (e.g. a document)
use an object, if emphasis is on activity (e.g. computing the cosine)
use a function.

These advantages outweigh by far lexical arguments (self. takes soooo long
to type) or temporary arguments (instance count is currently = 1).

Of course this is largely a matter of taste but I am a 'burnt child'
because I had to deal with the one-instance argument in multi-developer
projects and found the defender's code quite messy. :)
Other people have mentioned "code reuse". Again I don't see how a class
helps to make code reusable.
Inheritance.

I find methods in a class more difficult to reuse than simple function
> definitions. (unless there are multiple instances.)

Why? Methods are functions with an instance argument:

class person:
def tellName(self):
print self.name
Peter

Mit freundlichen Gruessen,

Peter Maas
 
R

Ryan Paul

Please don't do that. While it's true that the first parameter of a
class method can be named anything, the use of "self" is so
overwhelmingly ubiquitous it might as well be a standard. Using
anything else is just going to make your code more difficult for anybody
else to read and understand.

Typing is cheap. Thinking is expensive. And, yes Aahz, you can quote
me on that :)

I dont conform to a bad standard just because it's a standard. If I did, I
would be using java instead of a dynamic language like python. If other
people dont like it, thats too bad- they dont have to use my code.
 
G

Grant Edwards

I see the value of a class when two or more instances will be
created, but Python programmers regularly use a class when
there will only be one instance. What is the benefit of this?

1) Because people are notoriously bad and predicting the
future. Their guesses at what "will be" are often wrong.

If you use a class, then you can add a second instance
later when you figure out what the customer really wanted.

2) I find it often helps me think through the problem and
arrive at a more structured, easily maintained solution
compared to a bunch of random functions.
It has a disadvantage of a whole lot of "self." being required
everywhere, making the code less readable.

In some cases (particulary mathematical computations), the
self's can reduce readability. A few local variables can fix
that.
Also, since a strength of Python is rapid application
development, it slows one down to have to put in all those
self.'s.

I've never seen any project where the speed of development was
limited by typing speed.
The code seems much cleaner to me without classes that have
only one instance.

Until the requirements change (or are actually discovered), and
you need more than one instance.
 
P

Peter Hickman

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.

This is a lot like putting code in functions. "Its only called in one place, why put it in a function, why not just leave it where it is?" I had a conversation with a dBase
programmer many years ago on just these lines and what it came down to was this.

for x = 1 to length(orderitems)
calculate_tax(orderitems[x], .175)
next

(forgive the pseudo code) is easier to read and the intent of the code is much clearer, and also we had 24 * 80 screens and so you could see much more of the 'flow' of the program
than if the code was in lined. Objects just take all that one step further.

order.calculate_tax( .175 )

Why read fifty lines of code to work out that tax is being calculated for each item in the order when you can read one line? How you achieve this is not all that important, functions
or classes only that the flow of the program can be comprehended quickly. Objects don't just make writing code easier but it makes *READING* code easier too, a very important plus
(ever had to maintain APL?)

Almost everything that I write becomes an object even the programs themselves.
 
J

Jeffrey Barish

I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be
one instance.
What is the benefit of this? It has a disadvantage of a whole lot of
"self."
being required everywhere, making the code less readable. Also, since
a strength of Python is rapid application development, it slows one
down
to have to put in all those self.'s. The code seems much cleaner to
me
without classes that have only one instance. Oh, also, all the
methods of this class will have to have the instance name prepended to
them.

I would appreciate it if someone could explain the advantages of doing
this, or at least the sociological reasons why it occurs.

Mitchell Timin
As a novice Python programmer, I also thought about this question
recently and came up with one other rationale that no one else has
mentioned yet. (If this rationale is wrong, I would value
elucidation.) An instance also retains state whereas a function does
not (because the instance continues to exist). For example, if you
create the function

def assigner():
x = 2

the variable x exists only when test runs. A second function printer()

def printer():
print x

will not print the value assigned to x in assigner. (You get a
traceback because global variable x is not defined.) If you want x to
continue to exist after assigner runs, you must declare it global.
Thus, with

def assigner():
global x
x = 2

printer() will print the value assigned to x in assigner. When assigner
is a method, you can cause x to continue to exist by prepending self.
All variables with self prepended have global scope within the
instance. Thus,

class tester:
def assigner(self):
x = 1
def printer(self):
print x # global variable x not defined
t = tester()
t.assigner()
t.printer()

will not work (for the same reason it does not work with the functions
above), whereas

class tester:
def assigner(self):
self.x = 1
def printer(self):
print self.x # self.x is global within scope of instance
t = tester()
t.assigner()
t.printer()

prints 1.

It works to have a bunch of global variables in a module rather than a
single-instance class, but you may have to be more careful about name
clashes as the code expands. Using a single-instance class provides
another level of control over scope. Thus, you could have more than
one single-instance class in a module each defining its own namespace
whereas the code that lives in the other classes would otherwise have
to go in separate modules to provide the same degree of namespace
isolation. Also, with global declarations, it's hard to tell when you
read the code whether a variable has been declared global, whereas the
"self." prefix essentially announces that the corresponding variable
has been declared to have global scope within the instance.
 
D

Donald 'Paddy' McCarthy

Ryan said:
I dont conform to a bad standard just because it's a standard. If I did, I
would be using java instead of a dynamic language like python. If other
people dont like it, thats too bad- they dont have to use my code.
It's your code but might I suggest that you then be consistent in your
naming convention to aid re-use?
- Pad.
 
V

Ville Vainio

Ryan> the line. It's a good OO strategy. I do understand your
Ryan> dislike of 'self'. It does seem like clutter. In my code, I
Ryan> shorten it to 's'. In ruby, class variables are prefixed
Ryan> with an '@', which makes them easier to discern in code, and
Ryan> it is easier than typing 'self'. I wish python had something

Prefixing names with symbols like $ and @ is a great idea - it makes
the "nouns" (variables) stand out from "verbs", and makes the code
flow like a natural language, making reading it easy and writing it
fun!

On a more serious note, you could consider creating a binding for @
that inserts "self.". @ is almost never used in Python, so it should
be pretty safe.

Ryan> like that. I also think that having to specify the class
Ryan> variable in every function definition is a bit silly. Ruby
Ryan> gets rid of that too.

You might want to create a preprocessor that adds "self" to all
in-class definitions that have @, and convert @hei to self.hei. Voila,
Ruby non-silliness.

The idea could be extended to provide a "Python shorthand", which
would expand to full-blown Python:

d hello x y: -> def hello(x,y):


c hello baseclass:
d init arg1 arg2: # expand to __init__
.x = arg1
.y = arg2
d sayhi:
p "hi!"
.x = 555



o = hello 12 13

p o.x + o.y # prints 25

o.sayhi

p o.x # prints 555


Actually, while this would make zero sense for language-as-such, it
might turn out to be a fun way to hammer out that first ultra-rapid
prototype. At the moment something comes up that needs the
explicitness of Python (say, after 45 minutes of hacking), the
shorthand can be expanded to Python (optimally with M-x
py-expand-shorthand).

I find that I write Python code quite fast already, but some phases of
the coding process (esp. the implementation of classes) could be
further accelerated by this shorthand, mostly due to alleviating the
need to use the shift-key. ":" should still be there to enable the use
of python-mode.el.

The implementation of the shorthand could be pretty ad-hoc, with
possibly ambigous grammar. The shorthand would never be shipped
unexpanded anyway.
 
S

SeeBelow

Peter said:
I see the value of a class when two or more instances will be created,
but Python programmers regularly use a class when there will only be one
instance.

This is a lot like putting code in functions. "Its only called in one place, why put it in a function, why not just leave it where it is?" I had a conversation with a dBase
programmer many years ago on just these lines and what it came down to was this.

for x = 1 to length(orderitems)
calculate_tax(orderitems[x], .175)
next

(forgive the pseudo code) is easier to read and the intent of the code is much clearer, and also we had 24 * 80 screens and so you could see much more of the 'flow' of the program
than if the code was in lined. Objects just take all that one step further.

order.calculate_tax( .175 )

Why read fifty lines of code to work out that tax is being calculated for each item in the order when you can read one line? How you achieve this is not all that important, functions
or classes only that the flow of the program can be comprehended quickly.

I see the value of replacing many lines of code by a function
definition, for readability, even if that only happens once. In fact I
regularly do this. But does using a class acheive this better than a
function? It seems to me that a function is simpler and clearer.

m

--
"Many are stubborn in pursuit of the path they have chosen, few in
pursuit of the goal." - Friedrich Nietzsche

http://annevolve.sourceforge.net is what I'm into nowadays.
Humans may write to me at this address: zenguy at shaw dot ca
 
A

Andrew Koenig

Prefixing names with symbols like $ and @ is a great idea - it makes
the "nouns" (variables) stand out from "verbs", and makes the code
flow like a natural language, making reading it easy and writing it
fun!

Interesting idea. Let's try it with English, using @ for nouns and $ for
verbs:

$Prefixing @names with @symbols like $ and @ $is a great @idea - it $makes
the "@nouns" (@variables) $stand out from "@verbs" and $makes the @code
$flow like natural @language, $making $reading it easy and $writing it fun!

See how much easier the modified text is to read? :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top