473,785 Members | 2,421 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why a class when there will only be one instance?

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
Jul 18 '05
34 4768
Se******@SeeBel ow.Nut wrote:
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
p = person()
p.name = 'Peter'
intro_c = person.tellName
intro_c(p) Peter intro_i = p.tellName
intro_i()

Peter

Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplu sr.de
-------------------------------------------------------------------
Jul 18 '05 #11
On Tue, 25 May 2004 21:20:02 -0400, Roy Smith wrote:
Ryan Paul <se*******@sbcg lobal.net> wrote:
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 :-)


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.

Jul 18 '05 #12
On 2004-05-26, Se******@SeeBel ow.Nut <Se******@SeeBe low.Nut> wrote:
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.

--
Grant Edwards grante Yow! If I felt any more
at SOPHISTICATED I would DIE
visi.com of EMBARRASSMENT!
Jul 18 '05 #13
Se******@SeeBel ow.Nut wrote:
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(orderite ms)
calculate_tax(o rderitems[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.
Jul 18 '05 #14
Ryan Paul wrote:
On Tue, 25 May 2004 21:20:02 -0400, Roy Smith wrote:

Ryan Paul <se*******@sbcg lobal.net> wrote:
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
overwhelmingl y 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.

It's your code but might I suggest that you then be consistent in your
naming convention to aid re-use?
- Pad.

Jul 18 '05 #15
>>>>> "Ryan" == Ryan Paul <se*******@sbcg lobal.net> writes:

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.

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #16
Se******@SeeBel ow.Nut wrote:
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.
--
Jeffrey Barish
Jul 18 '05 #17
In article <ro************ ***********@rea der2.panix.com> ,
Roy Smith <ro*@panix.co m> wrote:

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


Heh. It's in my database now.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"He's Quebecois. He puts mayonnaise on *everything*." --*******@virulen t.org
Jul 18 '05 #18
Peter Hickman wrote:

Se******@SeeBel ow.Nut wrote:
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(orderite ms)
calculate_tax(o rderitems[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
Jul 18 '05 #19
"Ville Vainio" <vi***@spammers .com> wrote in message
news:du******** ********@amadeu s.cc.tut.fi...
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? :-)
Jul 18 '05 #20

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

Similar topics

4
8580
by: Sibyl | last post by:
Is there any way to get the name of a class without an instance (i.e., object of the class)? I am working with log4j, and would like a uniform way to name loggers without typing in the name of the class for each individual class. For example, ------------ import org.apache.log4j.Logger; public class Foo { ...
18
6957
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
4
1907
by: Donnal Walter | last post by:
This is a question about Python patterns or idioms. Over a period of time, I have evolved a pattern of usage that seems to work better for me than other ways I tried previously, but in writing some documentation I don't know what to call this syntax or how best to describe it. I have not seen it used in other places. The somewhat longish version is that I have implemented an MVP (model-view-presenter) architecture where each "presenter"...
9
2159
by: flarkblark | last post by:
I recently had the displeasure of looking at the code required to implement the pop-up menus used in a pulldown menu system for a webpage. The sheer amount of Javascript required was amazing and frankly revolting. It is as though the software "engineers" have been thrown out and replaced with "programmers". That is to say, it is a sophomoric hack job, a hideous kludge.
1
2526
by: Belebele | last post by:
I would like to have the compiler bind a Base class const reference to a temporary object of a Derived class when calling another class constructor. Please see the code below: class Base {}; class Derived: public Base {}; class Foo { public:
5
1420
by: Yarco | last post by:
When using c++, we could do: using abc = xxx.yyy; // am i right? When using python we could do: import abc.efg as efg When will php support: class My_Best_Class {
1
1271
by: hhhhhhhh | last post by:
What is a class variable or instance variable? I am still confused. Suppose I have the code like this: public class SavingAccount { private double annualInterestRate = 0; private double savingsBalance; }
2
1520
by: Damfino | last post by:
Hi all, Newbie question here wrt defining a class that will work on bits read from a binary file. How would you go about doing it? As an example please look at the structure of my data given below. The data comes in 40 byte packets via stdin or a binary file. my_Data_pkt(){ syncByte (8bits) XML_type (2bits) XML_subtype (2bits) record_value (3bits)
4
1686
by: Ken Fine | last post by:
I know about this: http://silverlight.net/forums/14.aspx and this: http://forums.asp.net/1127.aspx Silverlight Beta 2 was announced at TechEd. I was impressed. When does Silverlight get a first-class newsgroup? -KF
0
9645
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
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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
10091
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
8972
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...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
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.