Saturday, 15 August 2015

python - Make isinstance(obj, cls) work with a decorated class -



python - Make isinstance(obj, cls) work with a decorated class -

i have few classes need following:

when constructor called, if equal object (aka object same id) exists, homecoming object. otherwise, create new instance. basically,

>>> cls(id=1) cls(id=1) true

to accomplish this, i've written class decorator so:

class singleton(object): def __init__(self, cls): self.__dict__.update({'instances': {}, 'cls': cls}) def __call__(self, id, *args, **kwargs): try: homecoming self.instances[id] except keyerror: instance= self.cls(id, *args, **kwargs) self.instances[id]= instance homecoming instance def __getattr__(self, attr): homecoming getattr(self.cls, attr) def __setattr__(self, attr, value): setattr(self.cls, attr, value)

this want, but:

@singleton class c(object): def __init__(self, id): self.id= id o= c(1) isinstance(o, c) # returns false

how can prepare this? found related question, can't seem adapt solutions utilize case.

i know someone's gonna inquire me post code doesn't work, here go:

def singleton(cls): instances= {} class single(cls): def __new__(self, id, *args, **kwargs): try: homecoming instances[id] except keyerror: instance= cls(id, *args, **kwargs) instances[id]= instance homecoming instance homecoming single # problem: isinstance(c(1), c) -> false def singleton(cls): instances= {} def call(id, *args, **kwargs): try: homecoming instances[id] except keyerror: instance= cls(id, *args, **kwargs) instances[id]= instance homecoming instance homecoming phone call # problem: isinstance(c(1), c) -> typeerror

you can add together custom __instancecheck__ hook in decorator class:

def __instancecheck__(self, other): homecoming isinstance(other, self.cls)

python class python-2.7 python-decorators

No comments:

Post a Comment