[英]Create a new instance of a Class given an instance in Python
In Python, if I have an object, say x
, then how do I create a new object y
so that x
and y
are of the same class? 在Python中,如果我有一个对象,比如x
,那么如何创建一个新的对象y
使x
和y
属于同一个类?
In Java, the code I want would look something like this: 在Java中,我想要的代码看起来像这样:
Object y = x.getClass().newInstance();
You could probably do something like: 您可以做以下事情:
y = x.__class__()
or 要么
y = type(x)() #New style classes only
And, if you're wondering how to make a new style class, all you need to do is inherit from object
(or use python 3.x) 而且,如果您想知道如何创建一个新的样式类,您需要做的就是从object
继承(或使用python 3.x)
几乎和Java一样:
y = x.__class__()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.