Home > front end >  Create child class object using parent class instance
Create child class object using parent class instance

Time:09-25

lets say we have class A and it has one instance - x. How to make a child class of class A where I would be able to pass x as an argument and get all its parameters and pass it to child class object. precisely speaking I want to do something like this.

class A:
    def __init__(self, parameter1, parameter2):
        self.parameter1 = parameter1
        self.parameter2 = parameter2




class B(A):
    def __init__(self, Ainstance, someParameter):
        super().__init__(**Ainstance.__dict__)
        self.someParameter = someParameter

x = A(parameter1='1', parameter2='2')

x = B(x, someParameter='3')

print(x.parameter1)
print(x.parameter2)
print(x.someParameter)

the goal is to create a class where I would be able to get all the parameters of parent class object, and add my own attributes. The problem in the code above is I won't be able to do that with all classes because not all of them has __dict__ attribute.

CodePudding user response:

Instead of dict you could use the dir and getattr like this:

class A:
    def __init__(self, parameter1, parameter2):
        self.parameter1 = parameter1
        self.parameter2 = parameter2


 class B(A):
     def __init__(self, Ainstance, someParameter):
        parameters = {param: getattr(Ainstance, param) for param in dir(Ainstance) if not param.startswith("__")} 
        super().__init__(**parameters)
        self.someParameter = someParameter

For a more detailed explanation see: Get all object attributes in Python?

CodePudding user response:

I have this example code which I use to remind myself how to construct a proxy.

#soProxyPattern

class Example:
    def __init__(self):
        self.tag_name = 'name'
    def foo(self):
        return 'foo'
    def bar(self, param):
        return param
    
class Container:
    def __init__(self, contained):
        self.contained = contained
        self.user_name = 'username'

    def zoo(self):
        return 0
    
    def __getattr__(self, item):
        if hasattr(self.contained, item):
            return getattr(self.contained,item)
        #raise item

c = Container(Example())
print(c.zoo())
print(c.foo())
print(c.bar('BAR'))
print(c.tag_name)
print(c.user_name)

The output is:

0
foo
BAR
name
username

This shows that Container can have its own attributes (methods or variables) which you can access over and above all of the attributes of the contained instance.

  • Related