简体   繁体   中英

Python, how to convert an existing parent class object to child class object

*** To give a reason why I wanna do the following, I am trying to wrap the third-party tool and do more with it.

I am using a third-party tool, it returns an object as a result. (eg An object of class Person , which contains MANY attributes).

I want to declare a new class, eg Driver(Person) . Which contain everything that is in Person class, and more. I am NOT ALLOWED to modify the Person class.

I already have an existing Person object(returned from the third-party tool), how do I cast it into a Driver object? Not by initializing a new empty Driver object and copying everything one by one into it please... In my case, there's over 30 attributes and properties in the Person class, and Person class is not the only class I need to do this with. I have to do this with about 20 classes. This is why it is not practical for me to copy from scratch one by one for each class unless there's no other way.

class Person:
    def __init__(self):
        self._name = None

    @property
    def name(self):
        return self._name


class Driver(Person):
    def __init__(self):
        super().__init__()
        self._gender = None

    @property
    def gender(self):
        return self._gender

    def __str__(self):
        return f'{self.name} {self.gender}'

Given an instance of Person , cast it into a Driver . but imagine there's way more attributes in both classes. Currently, I basically just loaded the Person instance into a new Driver instance as an attribute. But I think there's gotta be a smarter way to do this.

Basically all attributes from a class live inside the magic __dict__ attribute. This dictionary-like object contains all the attributes defined for the object itself.

So a way to copy all attributes at once will be to copy the __dict__ attribute from a class to another either inside a method or from an instance like this:

a = Person()
b = Driver()
b.__dict__.update(a.__dict__)

Please note that if there are repeated attributes those will be overwritten so be careful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM