473,395 Members | 1,581 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

classes

Hello everyone

I have a problem with classes and hope someone can help me.
I'm used to Java and want to make a singleton class which would allow to
create only one instance of the class.
In Java it looks as follows:
public class DBConnection{
private static DBConnection instance = null;
private Conn conn = null; // it is supposed to be object returned be
pg.connect() method of the PyGreSQL module

/* a constructor must be private to forbid instantiation of the class */
private DBConnection(){
conn = new Conn();
}

public static DBConnection getInstance(){
if(instance == null)
instance = new DBConnection();
return instance;
}
};

How can I do the same in Python?
My main problems are:
1) how to declare a static field (class field not object field)
2) how to declare a static method
3) how to declare a private constructor (is it possible?)

Can someone help me or point me to some documentation with strong emphasis
on classes? It would be perfect if that documentation had some comparisons
with classes in Java or C++.

Best regards
Pablo
Jul 18 '05 #1
4 2203
"Pablo" <pa***@bogus.domain.org> wrote in message news:<pa****************************@bogus.domain. org>...
Hello everyone

I have a problem with classes and hope someone can help me.
I'm used to Java and want to make a singleton class which would allow to
create only one instance of the class. ....[snip]... How can I do the same in Python?
My main problems are:
1) how to declare a static field (class field not object field)
<nitpick>You can't. There are no variable declarations in
Python.</nitpick> You can use static fields, though.
class HasStaticField: .... field = 4
.... HasStaticField.field

4
2) how to declare a static method
class HasStaticMethod:
def method(arg0, arg1): # note the lack of "self"
# do something with arg0 and arg1
method = staticmethod(method)
3) how to declare a private constructor (is it possible?)


It's not possible (afaik) to define a private constructor. But it is
possible to enforce that a constructor can be called only once.

class SingletonError(Exception):
pass

class Singleton:
__instance = None
def __init__(self):
if Singleton.__instance is None:
# initialization code
Singleton.__instance = self
else:
raise SingletonError()
def getInstance():
if Singleton.__instance is None:
Singleton()
return Singleton.__instance
getInstance = staticmethod(getInstance)
Jul 18 '05 #2
[cut]
2) how to declare a static method


class HasStaticMethod:
def method(arg0, arg1): # note the lack of "self"
# do something with arg0 and arg1
method = staticmethod(method)


That's not exactly what I wanted.
I would prefer something like this:
class StaticMethod:
__instance = None
def __init__(self):
if StaticMethod.__instance is None:
StaticMethod.__instance = self
else:
raise Exception("Constructor may be invoked only once")
def getInstance():
if StaticMethod.__instance is None:
StaticMethod.__instance = StaticMethod()
return StaticMethod.__instance

m = StaticMethod.getInstance()
but Python does not allow to invoke any class method without providing an
instance of the class object

I've been thinking about Python classes and modules and found out that it
is possible in Python to create an object in some module and use a
reference to it from other modules. In Java it's not possible to create
any object outside of any class.
So my problem would be solved if I could create a class which would be
seen only in its module (something like private class). Then I could
create an object and simply use it across my application.
It would behave like a static object since it
wouldn't be possible to create another object in other modules (since the
class would be visible only it its module), and it also wouldn't be
possible to create another object in its module (there is no reason for
it).

Is it possible to create a class and forbid its use outside its module?
Thanks for a usefull reply.
Pablo
Jul 18 '05 #3
Quoth Michele Simionato:
Steven Taschuk <st******@telusplanet.net> wrote in message news:<ma**********************************@python. org>...

[...]
_the_instance = None
class MySingleton(object):
def __new__(self):
global _the_instance
if _the_instance is None:
_the_instance = object.__new__(self)
return _the_instance


Why are you using a global here and not [a class attribute]


The memory of that thread a little while back about using __del__
with singletons. If the instance is referenced by a class
attribute, the cyclic reference prevents the __del__ from being
used. If the cycle goes through a module attribute, though, the
zapping of module dicts during shutdown breaks the cycle and lets
the __del__ run. (Whether all this is true depends on the version
of Python, I think, but I don't know the details.)

This might be relevant to the OP, whose example was a singleton
representing the single database connection used by an entire
application -- in such a case, __del__ would be a natural place to
make sure the connection is closed properly.

I should have explained this bit of trickery. :(

[...]
Second approach: Use a metaclass. See
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/102187>

Unfortunately, I see that this recipe is not very recommendable. I have
just submitted a fix which seems to work:

[...]

Nice!

--
Steven Taschuk Aral: "Confusion to the enemy, boy."
st******@telusplanet.net Mark: "Turn-about is fair play, sir."
-- _Mirror Dance_, Lois McMaster Bujold

Jul 18 '05 #4
Steven Taschuk <st******@telusplanet.net> wrote in message news:<ma**********************************@python. org>...
Quoth Michele Simionato:
Steven Taschuk <st******@telusplanet.net> wrote in message news:<ma**********************************@python. org>...

[...]
_the_instance = None
class MySingleton(object):
def __new__(self):
global _the_instance
if _the_instance is None:
_the_instance = object.__new__(self)
return _the_instance


Why are you using a global here and not [a class attribute]


The memory of that thread a little while back about using __del__
with singletons. If the instance is referenced by a class
attribute, the cyclic reference prevents the __del__ from being
used. If the cycle goes through a module attribute, though, the
zapping of module dicts during shutdown breaks the cycle and lets
the __del__ run. (Whether all this is true depends on the version
of Python, I think, but I don't know the details.)

This might be relevant to the OP, whose example was a singleton
representing the single database connection used by an entire
application -- in such a case, __del__ would be a natural place to
make sure the connection is closed properly.

I should have explained this bit of trickery. :(

Thanks for the explation, I missed that thread.

Michele
Jul 18 '05 #5

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

Similar topics

1
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a...
9
by: Jack | last post by:
Hello I have a library of calculationally intensive classes that is used both by a GUI based authoring application and by a simpler non-interactive rendering application. Both of these...
9
by: Aguilar, James | last post by:
I know that one can define an essentially unlimited number of classes in a file. And one can declare just as many in a header file. However, the question I have is, should I? Suppose that, to...
12
by: Langy | last post by:
Hello I'm fairly new to C++ but have programmed several other languages and found most of c++ fairly easy (so far!). I've come to a tutorial on classes, could someone please tell me why you...
4
by: john townsley | last post by:
do people prefer to design classes for the particular job or for a rangle of tasks they might encounter now and in the future. i am doing some simple win32 apps and picking classes is simple, but...
2
by: joye | last post by:
Hello, My question is how to use C# to call the existing libraries containing unmanaged C++ classes directly, but not use C# or managed C++ wrappers unmanaged C++ classes? Does anyone know how...
18
by: Edward Diener | last post by:
Is the packing alignment of __nogc classes stored as part of the assembly ? I think it must as the compiler, when referencing the assembly, could not know how the original data is packed otherwise....
6
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by...
0
by: ivan.leben | last post by:
I am writing this in a new thread to alert that I found a solution to the problem mentioned here: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/7970afaa089fd5b8 and to avoid...
2
by: Amu | last post by:
i have a dll ( template class) ready which is written in VC++6. But presently i need to inherit its classes into my new C#.net project.so if there is some better solution with u then please give me...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...

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.