![](https://i-blog.csdnimg.cn/blog_migrate/649c5ff5479bdd63bf4248d11f27233d.jpeg)
(1) 创建和使用类
class Dog():
"""一次模拟小狗的简单尝试"""
# 在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
根据类创建实例
(2) 访问属性
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
输出
My dog's name is Willie.
My dog is 6 years old.
(3) 调用方法
my_dog2 = Dog('willie', 6)
my_dog2.sit()
my_dog2.roll_over()
输出
Willie is now sitting.
Willie rolled over!
(4) 创建多个实例
m_dog = Dog('willie', 6)
y_dog = Dog('lucy', 3)
print("My dog's name is " + m_do