yml 使用
# -*- encoding: UTF-8 -*-
"""
@File : workthree.py
@Time : 2020-6-3 14:08
@Author : Mokwing
@Email : 1010326277@qq.com
@Software: PyCharm
@Message :
"""
import yaml
class Animal:
# 该 Animal 类拥有的属性
def __init__(self, name, color, age, sex):
self.name = name
self.color = color
self.age = age
self.sex = sex
def call(self):
print("this animal can call.")
def run(self):
print("this animal can run.")
class Cat(Animal):
def __init__(self, name, color, age, sex, hair="short hair"):
super().__init__(name, color, age, sex)
self.hair = hair
def call(self):
print("this cat can miao miao.")
def work(self):
print("this cat can catch mice.")
print(f"{self.name} {self.color} {self.hair} {self.age} {self.sex} catch mice success.")
class Dog(Animal):
def __init__(self, name, color, age, sex, hair="long hair"):
super().__init__(name, color, age, sex)
self.hair = hair
def call(self):
print("this cat can wang wang.")
def work(self):
print("this dog can watch the house.")
print(f"{self.name} {self.color} {self.age} {self.sex} {self.hair}")
if __name__ == '__main__':
# 使用yml
with open("animal.yml") as f:
data = yaml.safe_load(f)
cat_data = data["cat"]
cat = Cat(cat_data["name"], cat_data["color"], cat_data["age"], cat_data["sex"])
cat.work()
dog_data = data["dog"]
dog = Dog(dog_data["name"], dog_data["color"], dog_data["age"], dog_data["sex"])
dog.work()
github 已更新。
已修改。新增 animail.yml 文件,修改init方法和调用方法
李新新-python实战(二) 作业
1、 自己写一个面向对象的例子-见-pythonCode-homework002 https://github.com/lixinxin2019/LaGou2Q.git
2、使用 yaml 来管理实例的属性:已补充