|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Static Python
Hi. I am trying to create a class that will allow only one instance of itself to be created. I was looking for something like static(in c++) for python. Is there something like this? Thanks!
|
|
#2
|
|||
|
|||
|
Quote:
What you want to do is to implement the Singleton pattern. You'll want to look at the Overriding the __new__ method section of Unifying types and classes. I've linked directly to the specific section where implementation is discussed but I recommend reading the entire essay. Last edited by percivall : April 20th, 2004 at 06:35 PM. |
|
#3
|
|||
|
|||
|
There are several ways to create singletons in Python, and they are covered in depth in the Python Cookbook on ASPN.
http://aspn.activestate.com/ASPN/Co...on/Recipe/52558 http://aspn.activestate.com/ASPN/Co...on/Recipe/66531 http://aspn.activestate.com/ASPN/Co...on/Recipe/66531 http://aspn.activestate.com/ASPN/Co...n/Recipe/102187 Some of them use deep Python magic, such as metaclasses. However the simplest way to create a singleton is to just use a module instead of a class. It is not as powerful as a class singleton since you can't use inheritance, but 99% of the time you don't need to. I generally avoid singletons since they tend to increase coupling between classes and make unit testing harder. Dave - The Developers' Coach |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Static Python |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|