Skip to content Skip to sidebar Skip to footer

How Do You Clone A Class In Python?

I have a class A and i want a class B with exactly the same capabilities. 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

Solution 1:

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:

defc():
    classClone(object):
        passreturn Clone

c1 = c()
c2 = c()
printid(c1)
printid(c2)

gives:

4303713312
4303831072

Solution 2:

I guess this is not what you wanted but its what the question seems to be asking for...

classFoo(object):
    defbar(self):
        return"BAR!"

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

print cls

x = cls()
print x.bar()

Solution 3:

maybe i misunderstood you question but what about wrapping A in B?

classA:deffoo(self):
        print "A.foo"classB:def__init__(self):
        self._i = A()

    def__getattr__(self, n):
        return getattr(self._i, n)

Solution 4:

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...

Post a Comment for "How Do You Clone A Class In Python?"