0

I have two classes that are inherited from the parent.

+------------+
|   Parent   |
|------------|
|attribute   |
+------------|
+------------+
      ^    ^
      |    +----------------+
      |                     |
+-----+------+        +-----+------+
|  SonSelf   |        | SonFromYaml|
|------------|        |------------|
|attribute   |        |            |
+------------|        +------------|
+------------+        +------------+
class Parent:
    def __init__(self):
        self.attribute = None

The first class fills in its attributes (calculates them) and writes itself to the yaml file.

class SonSelf(Parent):
    def __init__(self):
        super().__init__()
        self.attribute = 'not blank'
        with open('file.yml', 'w') as f:
            yaml.dump(self, f)

The second class reads these attributes from yaml.

class SonFromYaml(Parent):

    def __init__(self):
        super().__init__()
        with open('file.yml', 'r') as f:
            ret = yaml.load(f, Loader=yaml.Loader)
        self = ret

But for some reason the created object turns out to be empty.

>>> son_self = SonSelf()
>>> son_from_yaml = SonFromYaml()

>>> print("son_self.attribute: ", son_self.attribute)
>>> print("son_from_yaml.attribute: ", son_from_yaml.attribute)
son_self.attribute:  not blank
son_from_yaml.attribute:  None

The ret object itself is identical to the son_self object. I can see this in debug.

enter image description here

Is it possible to do so:

self = ret

Or it is necessary to forcibly copy each field from the object obtained when reading the yaml?

class SonFromYaml(Parent):

    def __init__(self):
        super().__init__()
        with open('file.yml', 'r') as f:
            ret = yaml.load(f, Loader=yaml.Loader)
        self.attribute = ret.attribute
  • 1
    ``self`` is just a local variable *referring to* the object. It is not the object itself. – MisterMiyagi Mar 26 '21 at 07:31
  • 1
    Note that ``pyyaml`` ships with various means to load/store an actual Python object. That means that that ``pyyaml`` will create the instance, though; an instance cannot load itself after being created, since it already exists by then – it can only *modify* itself to match the loaded data. – MisterMiyagi Mar 26 '21 at 07:35
  • Does this mean that this cannot be done in principle? That is, you need to copy the attributes? – Alexander Rakhmaev Mar 26 '21 at 07:55
  • Yes, if you want the instance to load itself. See the second-top answer in the duplicate on how to do that efficiently. – MisterMiyagi Mar 26 '21 at 08:02
  • Thank you, I understand. If you were to frame this with an answer, I marked it with a solution. – Alexander Rakhmaev Mar 26 '21 at 08:12

0 Answers0