I'm trying to implement the Singleton pattern in Python (2.7).
I've read severel posts (1, 2, 3, 4) about the implementation and I want to code my own version. (A version which I understand. I'm new to Python.)
So I'm creating the singleton with a method that will create my single object itself that will be returned on every Singleton.Instance()
call.
But the error message is always the same:
Traceback (most recent call last):
File "./test4.py", line 24, in <module>
print id(s.Instance())
File "./test4.py", line 15, in Instance
Singleton._instance = Singleton._creator();
TypeError: unbound method foobar() must be called with Singleton instance as first argument (got nothing instead)
Here I roll:
class Singleton(object):
_creator = None
_instance = None
def __init__(self, creator):
if Singleton._creator is None and creator is not None:
Singleton._creator = creator
def Instance(self):
if Singleton._instance is not None:
return Singleton._instance
Singleton._instance = Singleton._creator();
return Singleton._instance;
def foobar():
return "foobar"
s = Singleton( foobar )
print id(s.Instance())
Why is that? To be more specific: How do I call in a method a def
stored in a class variable in Python?
Aucun commentaire:
Enregistrer un commentaire