20201224-4

1-1
# dog class Dog(): """A simple attempt to model a dog.""" def __init__(self, name, age): """Initialize name and age attributes.""" self.name = name self.age = age def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate rolling over in response to a command.""" print(self.name.title() + " rolled over!") my_dog = Dog('willie', 6) your_dog = Dog('lucy', 3) print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + " years old.") my_dog.sit() print("\nMy dog's name is " + your_dog.name.title() + ".") print("My dog is " + str(your_dog.age) + " years old.") your_dog.sit() ---> My dog's name is Willie. My dog is 6 years old. Willie is now sitting. My dog's name is Lucy. My dog is 3 years old. Lucy is now sitting.

 

2-1
使用模块collections中的OrderedDict类。OrderedDict实例的行为 几乎与字典相同,区别只在于记录了键—值对的添加顺序
创建了OrderedDict 类的一个实例,并将其存储到favorite_languages中。
请注意,这里没有使用花括号,而是调用 OrderedDict()来创建一个空的有序字典,并将其存储在favorite_languages中
这是一个很不错的类,它兼具列表和字典的主要优点(在将信息关联起来的同时保留原来的 顺序)。
等你开始对关心的现实情形建模时,可能会发现有序字典正好能够满足需求。
# favorite languages

from collections import OrderedDict

favorite_languages = OrderedDict()

favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +
        language.title() + ".")

 

上一篇:Bean作用域、自动、手动、注解实现装配


下一篇:给属性赋值