您可以使用基类的现有实例创建子类的实例吗? [英] Can you create an instance of a subclass with an existing instance of the base class?
问题描述
你能用现有的
基类实例创建一个子类的实例吗?
这些东西在某些语言中是不可能的很难在
其他人。我想知道这是否可以在python中完成,而不复制
基类实例,在我的情况下这是一个非常昂贵的对象。
任何想法?
谢谢,
-Sandra
Can you create an instance of a subclass using an existing instance of
the base class?
Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.
Any ideas?
Thanks,
-Sandra
推荐答案
In文章< 11 ********************** @ j33g2000cwa.googlegroups .com>,
" Sandra-24" < SA *********** @ yahoo.com>写道:
In article <11**********************@j33g2000cwa.googlegroups .com>,
"Sandra-24" <sa***********@yahoo.com> wrote:
你能使用基类的现有实例创建一个子类的实例吗?
Can you create an instance of a subclass using an existing instance of
the base class?
我认为你太认真地对待Python的OO-ness了。 Python的优点之一就是它可以_look_像OO语言,而不是实际上是OO的
。
I think you''re taking Python''s OO-ness too seriously. One of the
strengths of Python is that it can _look_ like an OO language without
actually being OO.
使用新式类,您可以找到类的子类,然后
您可以实例化您想要的子类。假设你有两个类
A和B,B是A的子类,A是一个新式的类。现在你有一个名为a的实例,你可以执行以下操作:
b = a .__ class __.__ subclasses__ ()[0]()
With new-style classes you can find out a class'' subclasses and then
you can instantiate the subclass you want. Suppose you have two classes
A and B, B is a subclass of A, A is a new-style class. Now you have an
A''s instance called "a", to instance B you can do the following:
b = a.__class__.__subclasses__()[0]()
Sandra-24写道:
Sandra-24 wrote:
你能创建一个实例吗?使用基类的现有实例的子类?
这些东西在某些语言中是不可能的,或者在其他语言中是非常困难的。我想知道这是否可以在python中完成,而不复制
基类实例,在我的情况下这是一个非常昂贵的对象。
Can you create an instance of a subclass using an existing instance of
the base class?
Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.
你可以改变分配给__class__
属性的实例类。新类甚至不需要成为旧类的子类:
You can change the class of an instance by assigning to the __class__
attribute. The new class doesn''t even need to be a subclass of the old:
A类(对象) :
.... def __init __(self,name):
.... self.name = name
.... def show(self ):print self.name
.... a = A(alpha)
a.show()
alpha class B(object):
.... def show(self):print self.name.upper()
.... a .__ class__ = B
a.show()
class A(object): .... def __init__(self, name):
.... self.name = name
.... def show(self): print self.name
.... a = A("alpha")
a.show() alpha class B(object): .... def show(self): print self.name.upper()
.... a.__class__ = B
a.show()
ALPHA
Peter
ALPHA
Peter
这篇关于您可以使用基类的现有实例创建子类的实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!