2

I have a class:

class Foo():
    def __init__(self):
        self.a = 1

and it's child:

class Bar(Foo):
    def __init__(self, foo, string):
        Foo.__init__(self)
        self.b = string

I need to create a Foo()-object from Bar()-object How can I do this?

i.e:

a = Foo()
a.a = 2
print a.a

b = Bar(a, 'ololo')

print b.a
print b.b

I get printed this:

2
1
ololo

and expecting this:

2
2
ololo

3 Answers3

0

I think you talk about copy constructor. Here you can find a way of how you can create it in python - Is this the equivalent of a copy constructor in Python?

import copy
class Bar(Foo):
    def __init__(self, foo, string):
        if foo:
            self.__dict__ = copy.deepcopy(foo.__dict__)
        else:
            Foo.__init__(self)

        self.b = string
Community
  • 1
  • 1
ndpu
  • 22,225
  • 6
  • 54
  • 69
  • 2
    This is dangerous - this only copies the references in the `dict`, meaning that the objects could end up linked by mutable objects. There is a reason `__copy__()` isn't implemented by default - it's not a trivial task. – Gareth Latty Apr 14 '13 at 15:34
  • @Lattyware +1, deepcopy can help i think, and i agree that it dangerous but works in simple cases – ndpu Apr 14 '13 at 15:51
0

When you set a.a = 2, you set the variable only in the single instance of your Foo class, not change the variable in the class "blueprints" themselves. Therefore when using the Foo class as a parent class, the original self.a variable is kept: a = 1.

This means the child class Bar inherits the variable self.a = 1, which is why it has printed as it has in your example.

Other than this, I'm unsure as to what you're trying to achieve, sorry.

Pythonidae
  • 106
  • 4
-1

To use instances of "Foo" to set some variables of instances of "Bar" you don't need heritage. 'cause what you need isn't the Foo class, in fact you only need one Foo instance:

class Bar:
    def __init__(self,foo,string):
        self.b=string
        if isinstance(foo,Foo):
            self.a=foo.a
Dusk
  • 1,729
  • 10
  • 17