Форум сайта python.su
суть проблемы. есть два класса
class commonClass(object):
def __init__(self):
pass
def method(self):
pass
class subClass(commonClass):
def __init__(self):
pass
def otherMethod(self):
pass
Офлайн
Зависит от ситуации, но для простых случаев вроде должно работать…
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()
Отредактировано (Сен. 25, 2010 16:56:11)
Офлайн
спасибо
Офлайн
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
Отредактировано (Сен. 26, 2010 00:05:41)
Офлайн