Rishabh Kandari
Rishabh Kandari

Reputation: 160

Python Inheritence - Parent Object as parameter to child object

I am having some issues with an inheritence model. i want to create a new child object from a given parent object and i would like to access those properties. Here is a simplified model of my structure.

class foo:
def __init__(self,id,name):
    self.id = id
    self.name = name

class bar(foo):
    pass

new = foo(id='1',name='Rishabh')

x = bar(new)

print(x.name)

I want all the attributes from the new object to be inherited in the x object. Thanks

Upvotes: 0

Views: 2282

Answers (1)

wencakisa
wencakisa

Reputation: 5958

At first, as PEP8 Style Guide says, "Class names should normally use the CapWords convention." So you should rename your classes to be Foo and Bar.

Your task can be done by using object.__dict__ and by overriding the __init__ method in your child class (Bar)

class Foo:
    def __init__(self, id, name):
        self.id = id
        self.name = name


class Bar(Foo):
    def __init__(self, *args, **kwargs):
        # Here we override the constructor method
        # and pass all the arguments to the parent __init__()

        super().__init__(*args, **kwargs)


new = Foo(id='1',name='Rishabh')

x = Bar(**new.__dict__)
# new.__dict__() returns a dictionary
# with the Foo's object instance properties:
# {'id': '1', 'name': 'Rishabh'}

# Then you pass this dictionary as
# **new.__dict__
# in order to resolve this dictionary into keyword arguments
# for the Bar __init__ method

print(x.name)  # Rishabh

But this is not a conventional way of doing things. If you want to have an instance, that is a copy of another, you should probably use the copy module and do not do this overkill.

Upvotes: 2

Related Questions