我怎样才能知道对象是否存在?

时间:2016-01-15 05:09:58

标签: python python-3.x

我写了这段代码。我期待被展示" cat is None"。但是发生了错误。我想知道一个物体是否存在安全。我能怎么做?或者你有什么想法吗?

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

0 个答案:

没有答案