简体   繁体   English

你如何在Python中克隆一个类?

[英]How do you clone a class in Python?

I have a class A and i want a class B with exactly the same capabilities. 我有一个A类,我想要一个具有完全相同功能的B类。 I cannot or do not want to inherit from B, such as doing class B(A):pass Still i want B to be identical to A, yet have a different i: id(A) != id(B) Watch out, i am not talking about instances but classes to be cloned. 我不能或不想从B继承,例如做B(A)类:传递仍然我希望B与A相同,但有一个不同的i:id(A)!= id(B)注意,我不是在讨论实例,而是要克隆的类。

I'm pretty sure whatever you are trying to do can be solved in a better way, but here is something that gives you a clone of the class with a new id: 我很确定你想要做的事情可以用更好的方式解决,但是这里有一些东西可以让你克隆一个带有新id的类:

def c():
    class Clone(object):
        pass

    return Clone

c1 = c()
c2 = c()
print id(c1)
print id(c2)

gives: 得到:

4303713312
4303831072

I guess this is not what you wanted but its what the question seems to be asking for... 我想这不是你想要的,但它的问题似乎要求......

class Foo(object):
    def bar(self):
        return "BAR!"

cls = type("Bar", (object,), dict(Foo.__dict__))

print cls

x = cls()
print x.bar()

maybe i misunderstood you question but what about wrapping A in B? 也许我误解了你的问题但是在B中包装A怎么样?

class A:

    def foo(self):
        print "A.foo"

class B:

    def __init__(self):
        self._i = A()

    def __getattr__(self, n):
        return getattr(self._i, n)

You can clone the class via inheritance. 您可以通过继承克隆该类。 Otherwise you are just passing around a reference to the class itself (rather than a reference to an instance of the class). 否则,您只是传递对类本身的引用(而不是对类的实例的引用)。 Why would you want to duplicate the class anyway? 你为什么要复制课程呢? It's obvious why you would want to create multiple instances of the class, but I can't fathom why you would want a duplicate class. 很明显,为什么你想创建类的多个实例,但我无法理解为什么你想要一个重复的类。 Also, you could simply copy and paste with a new class name... 此外,您只需复制并粘贴一个新的类名...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM