473,785 Members | 2,458 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
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-05-26T18:00:29Z, "Andrew Koenig" <ar*@acm.org> writes:
$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!


I ran that through Perl and got a mildly functional spreadsheet application.
A few more lines, and I think you could've added the flight simulator.
- --
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAtOya5sR g+Y0CpvERAm5OAJ 9sjhZPhu2iVU3pd H+jiM2eb3udowCe NpJr
O9ca+ZS3J4lFI5g nQKTOOZI=
=NXmP
-----END PGP SIGNATURE-----
Jul 18 '05 #21
Ville Vainio wrote:
>> "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.


Now that's a great idea! Not the sigils stuff, I switched from Perl to
Python for a reason, I was putting sigils in my English, C, and so on.

I love the shorthand tho:

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

That seems unambiguous to me and I could see a parser for that language that
would output equivalent Python. It just so happens that there was an
article on slashdot a few minutes ago recommending a similar principle
(http://www.third-bit.com/~gvwilson/xmlprog.html).

The rules of the game:
*This language must require less typing or be easier to use than Python.
*Each construct must map to an equivalent Python construct unambiguously.
*We always generate the Python equivalent ASAP and throw out the shorthand.
(You might want sigils, but I don't. Only Python is portable.)

There are two paths, have the IDE convert each line to Python when you hit
'\n' or as a batch. The first method would allow it in Python shells.

One final thought, it should be added to IPython. I'm not associated with
IPython in any way, but it already supports alternate Python syntax and
generates genuine Python.
In [6]: range 3
------> range(3)
Out[6]: [0, 1, 2]
This is a very good idea. I wonder how hard it will be.

Josh Gilbert
Jul 18 '05 #22
>>>>> "Andrew" == Andrew Koenig <ar*@acm.org> writes:

Andrew> "Ville Vainio" <vi***@spammers .com> wrote in message
Andrew> 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!


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

Lest the humor (of contorted inside variety, I admit) be missed, it
was a parody of Larry Wall's argument for why $ prefix does not in
fact suck.

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #23
Ville Vainio wrote:
>> "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!


As a preliminary measure you might want to apply the following patch:

*** this.py 2002-02-08 21:41:34.000000 000 +0100
--- $this.py 2004-05-27 09:34:01.000000 000 +0200
***************
*** 18,24 ****
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
! Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

d = {}
for c in (65, 97):
--- 18,24 ----
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
! $Flzoby $cersvkrf @ner &bar !@ubaxvat &terng $vqrn -- /yrg'f @qb &!zber
&bs $gubfr!"""

d = {}
for c in (65, 97):

As you can see I didn't find the proposed distinction between nouns and
verbs always convenient. A little randomness immediately leads the eye to
the really unimportant stuff - just like the ugly new hat of a friend you
haven't seen for some time.
Yet another case where practicality beats purity :-)

Peter

Jul 18 '05 #24
Ville Vainio wrote:
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.


This is an editor job. Good programming editors allow to expand
abbreviations, so there is no need to clutter the language
definition or write a preprocessor.

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 #25
>>>>> "Josh" == Josh Gilbert <jg************ ***********@uvm .edu> writes:
Josh> Now that's a great idea! Not the sigils stuff, I switched
Josh> from Perl to Python for a reason, I was putting sigils in my
Josh> English, C, and so on.

I agree - the $ @ stuff was a (bad) joke, as I said elsewhere.

Josh> There are two paths, have the IDE convert each line to
Josh> Python when you hit '\n' or as a batch. The first method
Josh> would allow it in Python shells.

Live conversion would probably bring less surprises.

Josh> This is a very good idea. I wonder how hard it will be.

At least it doesn't *seem* difficult. It might even be easy enough to
do with regexps!

Some syntax brainstorming again:

d f x,y,z=12: -> def f(x,y,z=12): (, is one keystroke just like space)

d f x,y: -> def f(self,x,y): (d with indent, add self)

p x; r x; -> print x; return x
a.b 1,2 ; a..b ; .a; -> a.b(1,2); a.b ; self.a;

Sounds like a potentially fun emacs project, and the style of
programming that could be appreci8ed by TXT MSG gener8n :-).

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #26
>>>>> "Peter" == Peter Maas <pe********@mpl usr.de> writes:

Peter> Ville Vainio wrote:
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.


Peter> This is an editor job. Good programming editors allow to
Peter> expand abbreviations, so there is no need to clutter the
Peter> language definition or write a preprocessor.

Cluttering the language definition was the furthest thing from my
mind. The point of the preprocessor suggestion was that there is no
need to abandon Python if 'self' is all that troubles you. If one
doesn't bear to look at it, it can be made invisible. Running every
Python script you write through a preprocessor is not a worse solution
that switching to Ruby.

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #27
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ville Vainio wrote:
>> "Josh" == Josh Gilbert <jg************ ***********@uvm .edu> writes:

Josh> Now that's a great idea! Nlanguageigils stuff, I switched
Josh> from Perl to Python for a reason, I was putting sigils in my
Josh> English, C, and so on.

I agree - the $ @ stuff was a (bad) joke, as I said elsewhere.

Josh> There are two paths, have the IDE convert each line to
Josh> Python when you hit '\n' or as a batch. The first method
Josh> would allow it in Python shells.

Live conversion would probably bring less surprises.

Josh> This is a very good idea. I wonder how hard it will be.

At least it doesn't *seem* difficult. It might even be easy enough to
do with regexps!

Some syntax brainstorming again:

d f x,y,z=12: -> def f(x,y,z=12): (, is one keystroke just like
space)

d f x,y: -> def f(self,x,y): (d with indent, add self)

p x; r x; -> print x; return x
a.b 1,2 ; a..b ; .a; -> a.b(1,2); a.b ; self.a;

Sounds like a potentially fun emacs project, and the style of
programming that could be appreci8ed by TXT MSG gener8n :-).


Oh my. It's utterly trivial with IPython. As in the framework is all there,
just plug in your rules. My implementation currently uses only regex's
which could lead to errors in string literals or comments. However, it
works.

A more interesting implementation would be to write a full-blown parser for
the shorthand language with a simple lookup table to translate it to real
Python. I might get around to it, but probably not. I can't think of a way
to save much more typing without being overly obscure.

Well that was fun. I guess the only thing left for me to say is the vague
handwaving of suggesting that the script could decode to another language,
any language as long as you can define a one to one correspondence of
terminals. So I could write Java that looked an awful lot like Python.
Probably a bad idea.

Josh

- --
http://www.uvm.edu/~jgilbert/public_key.gpg
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAtkX13TW YZBkZ2IsRAiylAJ 9oaFGHFoN0aRE8a GWxmyZIDt2c6ACb BBfB
FG/DVh1ApDQyBvKRQe TW61g=
=7Nwd
-----END PGP SIGNATURE-----
Jul 18 '05 #28
[Se******@SeeBel ow.Nut]
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?
There are two advantages for me:

1) It helps at keeping related data and actions together within a named
concept. This further increases legibility and eases maintenance.

2) The global namespace stays much cleaner. (A side effect is that I
never need the `global' declaration in practice.)
It has a disadvantage of a whole lot of "self." being required
everywhere, making the code less readable.
While those `self.' are a bit of a clutter indeed, they help me to read
that this routine is calling this other one within the same conceptual
part of the whole program, and as such, they had documentation value.
Oh, also, all the methods of this class will have to have the instance
name prepended to them.


It would be `self.' within the class itself, and the instance name
within foreign classes. This habit stresses the relations between the
parts of the program and eases a better understanding of the whole.

--
François Pinard http://www.iro.umontreal.ca/~pinard

Jul 18 '05 #29
François Pinard wrote:

....
It would be `self.' within the class itself, and the instance name
within foreign classes. This habit stresses the relations between the
parts of the program and eases a better understanding of the whole.


Just a little observation:
If you really want the class and the instance to be the same,
well, you can take a module.
In a sense, this *is* a class and the only instance.

ciao - chris
--
Christian Tismer :^) <mailto:ti****@ stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
Jul 18 '05 #30

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
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
9950
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
6739
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();...
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
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.