S*******s 发帖数: 13043 | 1 I got an error if I want to run test.py:
@singleton
NameError: name 'singleton' is not defined
if I combine the two files, it would be fine.
what is right way to import decorator?
#in module Singleton.py
def singleton(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theClass, args, str(kwargs))
if key not in classInstances:
classInstances[key] = theClass(*args, **kwargs)
return classInstances[key]
return getInstance
#in module test.py
import Singleton
@singleton
class A:
""" test class """
def __init__(self, key=None, subkey=None):
self.key = key
self.subkey = subkey
def __repr__(self):
return "A(id=%d, %s,%s)" % (id(self), self.key, self.subkey)
def tests():
""" some basic tests """
testCases = [ (None, None), (10, 20), (30, None), (None, 30) ]
instances = set()
instance1 = None
instance2 = None
for key, subkey in testCases:
if key == None:
if subkey == None: instance1, instance2 = A(), A()
else: instance1, instance2 = A(subkey=subkey), A(
subkey=subkey)
else:
if subkey == None: instance1, instance2 = A(key), A(key)
else: instance1, instance2 = A(key, subkey=subkey),
A(key, subkey=subkey)
print("instance1: %-25s" % instance1, " instance2: %-25s" %
instance2)
assert instance1 == instance2
assert instance1.key == key and instance1.subkey == subkey
instances.add(instance1)
assert len(instances) == len(testCases)
if __name__ == '__main__':
tests() | f*******n 发帖数: 12623 | 2 A decorator is just a regular function that you use by putting @ in front of
it. So you just import it the same way you import any other variable
import Singleton
@Singleton.singleton
or
from Singleton import singleton
@singleton | S*******s 发帖数: 13043 | 3 Thanks. still confused, when we import sth, when do we need add the module
name as prefix when we need refer to the element in the imported module?
Also, can you explain a little on how the getinstance get called?
of
【在 f*******n 的大作中提到】 : A decorator is just a regular function that you use by putting @ in front of : it. So you just import it the same way you import any other variable : import Singleton : @Singleton.singleton : or : from Singleton import singleton : @singleton
| f*******n 发帖数: 12623 | 4 If you import something using "import xxx", then just the module is imported
. You must add the module name as prefix to use the things inside.
import math
math.sqrt(4)
If you import something using "from xxx import ...", then those things you
list are imported directly into the namespace.
from math import sqrt
sqrt(4)
You can import everything from a module into the namespace like this:
from math import *
sqrt(4) |
|