How do you clone a class in Python?

I have class A and I want class B with exactly the same capabilities. I cannot or do not want to inherit from B, for example, by executing class B (A): pass However, I want B to be identical to A, but have a different i: id (A)! = Id (B) Beware I'm not talking about examples, but classes that need to be cloned.

+6
python
source share
5 answers

I am sure that everything you are trying to do can be solved better, but here is something that gives you a clone of the class with a new id:

def c(): class Clone(object): pass return Clone c1 = c() c2 = c() print id(c1) print id(c2) 

gives:

 4303713312 4303831072 
+13
source share

I think this is not what you wanted, but what seems to be asking a question ...

 class Foo(object): def bar(self): return "BAR!" cls = type("Bar", (object,), dict(Foo.__dict__)) print cls x = cls() print x.bar() 
+7
source share

I may have misunderstood you, but what about packing A to B?

 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) 
0
source share

You can clone a class through inheritance. Otherwise, you simply pass the reference to the class itself (and not the reference to the class instance). Why do you want to duplicate a class? Obviously why you want to create multiple instances of the class, but I cannot understand why you need a duplicate class. Alternatively, you can simply copy and paste with the new class name ...

-one
source share
 class C(object): pass class A(C): pass class B(C): pass 
-one
source share

All Articles