0

I wrote this code. I expected to be displayed "cat is None". But an error occurred. I would like to know whether an object exists or not safely. How can I do? Or do you have any idea?

import yaml

class AnimalModel:
    def __init__(self, raw_yaml):
        if raw_yaml is None:
            # When cat, return None indeed.
            return None
        self.name = raw_yaml.get("name")
        self.age = raw_yaml.get("age")


class ZooClass:
    def __init__(self, path):
        with open(path, 'r', encoding='utf-8') as text:
            raw_yaml = yaml.load(text)
            self.dog = AnimalModel(raw_yaml.get("dog"))
            self.cat = AnimalModel(raw_yaml.get("cat"))

            print(type(self.dog))  # <class '__main__.AnimalModel'>
            if self.dog is None:
                print("dog is None")
            else:
                print(self.dog.name, self.dog.age)  # done

            print(type(self.cat))  # <class '__main__.AnimalModel'>
            if self.cat is None:
                print("cat is None")   # I expected this, but didn't.
            else:
                print(self.cat.name + self.cat.age)  # done abd error. AttributeError: 'AnimalModel' object has no attribute 'name'

if __name__ == '__main__':
    sample = ZooClass("C:\zoo.yaml")

zoo.yaml

dog:
    name: "Michael"
    age:  10

# cat is None
#cat:
#    name: "Joshua"
#    age:  3
Maiko Ohkawa
  • 853
  • 2
  • 11
  • 28
  • 4
    You'll have to raise an exception if you don't want the object created. – thebjorn Jan 15 '16 at 05:14
  • You could move the file opening out of the `ZooClass` and pass in the file object. That eliminates one error that could happen in the constructor. For errors relating to yaml parsing, exceptions would be the way to go. – Paul Rooney Jan 15 '16 at 05:28
  • 1
    You could check if `raw_yaml.get("cat")` is None before creating the object. `if raw_yaml.get("cat") is not None: self.cat = AnimalModel(raw_yaml.get("cat"))` – Steven Summers Jan 15 '16 at 06:52
  • Thank you, I try using `raise` and `except`. If I can't write well, I will adopt the Steven Summers's draft. – Maiko Ohkawa Jan 15 '16 at 17:21
  • Hmm, I can't understand Paul Rooney's comment as well. Do you mean like that code? ` if __name__ == '__main__': with open(path, 'r', encoding='utf-8') as text: raw_yaml = yaml.load(text) ZooClass(raw_yaml)= – Maiko Ohkawa Jan 15 '16 at 17:21

0 Answers0