[Python] what is best way to copy a class without using inheritance in Python [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want a class 'child' to inherit all the properties of class 'parent' but this is going to be the exception rather than the rule. In more than 95% of the cases this is not going to happen, so what is the best way in Python to have a child class copy all of the attributes of the parent? Right now, I'm doing it this way (see below) but I have a hunch that there is a better way to do this. In the example below, of course it's better for the child to simply inherit from the cool_class, but like I said, with my current code it's not feasible to do it that way.

    class cool_class():
    def __init__(self):
    self.hey_you = 1



    def copy_class(child, parent):

    attributes = [x for x in parent.__dict__]
    for attribute in attributes:
    if not attribute.startswith("__"):
    setattr(child, attribute, getattr(parent, attribute))

    ins = cool_class()
    ins.get_off_my_cloud = 1
    ins2 = cool_class()
    copy_class(ins2,ins)
    assert ins2.get_off_my_cloud == 1

    Continue reading...

Compartilhe esta Página