Найти - Пользователи
Полная версия: Как прокастит один класс в другой
Начало » Python для экспертов » Как прокастит один класс в другой
1
Thanatoz
суть проблемы. есть два класса
class commonClass(object):
def __init__(self):
pass

def method(self):
pass

class subClass(commonClass):
def __init__(self):
pass

def otherMethod(self):
pass
в результате выполнения кода я получаю объект класса commonClass.
object = commonClass()

Мне из него нужно получить subClass, чтобы использовать методы класса subClass.otherMethod()

Как это сделать?
Zubchick
Зависит от ситуации, но для простых случаев вроде должно работать…
class commonClass(object):
def __init__(self):
self.x = 1

def method(self):
print 'one'

class subClass(commonClass):
def __init__(self):
pass

def otherMethod(self):
print 'other'

def to_sub(obj, Sub):
buf = Sub()
objd = obj.__dict__
for key in objd:
setattr(buf, key, objd[key])
return buf

a = commonClass()
a = to_sub(a, subClass)
a.otherMethod()
other
In : a.x
Out: 1
Thanatoz
спасибо
bw
class commonClass(object):
def __getstate__(self):
return dict(foo = self.foo)

class subClass(commonClass):
def __setstate__(self, state):
self.foo = state['foo']
Всё остальное – хак :-).

Пример хака:
>>> object = commonClass()
>>> object.otherMethod()
Traceback (most recent call last):
...
AttributeError: 'commonClass' object has no attribute 'otherMethod'
>>> subClass.otherMethod(object)
Traceback (most recent call last):
...
TypeError: unbound method otherMethod() must be called with subClass instance as first argument (got commonClass instance instead)
>>> isinstance(object, commonClass)
True
>>> isinstance(object, subClass)
False
>>> object.__class__ = subClass
>>> object.otherMethod()
>>> isinstance(object, commonClass)
True
>>> isinstance(object, subClass)
True
..bw
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB