Un-Wrap or De-Inherit an object

Viewed 53

A code block I do not have access to, returns an object that is "wrapped" or rather inherited from a base class, that I want to recover. The wrapper is harmful, I want to get rid of it. Is there a way to upcast to the parent class? To unwrap the object? To disinherit it?

I prepared a simple example: Is it possible to manipulate the u object in a way that it will be a Person object and say hello in a nice way?

class Person():
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hi, my name is " + self.name)

class Unfriendly_Person(Person):
    def say_hello(self):
        print("Leave me alone!")

u = Unfriendly_Person("TJ")
u.say_hello()
1 Answers

You might assign to __class__, so

class Person():
    def __init__(self, name):
        self.name = name
    def say_hello(self):
        print("Hi, my name is " + self.name)

class Unfriendly_Person(Person):
    def say_hello(self):
        print("Leave me alone!")

u = Unfriendly_Person("TJ")
u.__class__ = Person
u.say_hello()

output:

Hi, my name is TJ

But rememeber that this will jettison all methods from Unfriendly_Person even these not defined in Person.

Related