How do you clone a class in Python?

前端 未结 4 1933
遥遥无期
遥遥无期 2021-01-03 01:03

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 ident

相关标签:
4条回答
  • 2021-01-03 01:35

    maybe i misunderstood you question but what about wrapping A in 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 讨论(0)
  • 2021-01-03 01:43

    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:

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

    gives:

    4303713312
    4303831072
    
    0 讨论(0)
  • 2021-01-03 01:46

    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()
    
    0 讨论(0)
  • 2021-01-03 01:53

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

    0 讨论(0)
提交回复
热议问题