Python singleton again / how to use class attributes? -
i have singleton class in python java "static class attributes". read several posts existing on python singletons , can not find solution except using simple module singleton.
is there way extends code (pep318) use "static class attributes" can access functions?
def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class myclass: ...
tbh, i've found singleton anti-pattern.
if want object ever have single instance, why bother instantiating anything? like...
class mycounter(object): count = 0 @classmethod def inc(cls, delta=1): cls.count += delta >>> mycounter.count 0 >>> mycounter.inc() >>> mycounter.count 1 >>> mycounter.inc(5) >>> mycounter.count 6
Comments
Post a Comment