Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you clone a class in Python?

Tags:

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 A, yet have a different i: id(A) != id(B) Watch out, i am not talking about instances but classes to be cloned.

like image 898
Francois Avatar asked Dec 19 '09 18:12

Francois


People also ask

How do you copy a class in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

Can you copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy.

What does Copy () do in Python?

The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list.


1 Answers

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
like image 181
mthurlin Avatar answered Sep 27 '22 18:09

mthurlin