1、创建类,设置属性和给属性设定默认值,设置方法并访问类的属性;
2、利用类创建多个实例,以及调用类的方法的两种办法;
3、设置更新属性的函数,并更新实例的属性。
1 class dog(object): 2 """创建小狗类""" 3 4 def __init__(self, name, age): 5 """初始化参数,Python创建实例时,自动传入实参self,指向实例本身,以便访问属性和方法""" 6 self.name = name 7 self.age = age 8 ‘‘‘给属性指定默认值‘‘‘ 9 self.color = ‘white‘ 10 11 def sit(self): 12 ‘‘‘访问类的属性‘‘‘ 13 print(self.name.title() + ‘ is now siting.‘) 14 15 def roll(self): 16 print(self.name.title()+ ‘ is now rolling‘) 17 18 ‘‘‘通过方法修改属性的值‘‘‘ 19 def updateColor(self,color): 20 self.color = str(color) 21 print(self.name.title()+ "‘s color is " + str(color)) 22 23 ‘‘‘Method one 通过先给参数赋值,再带入到类形参中,创建一个实例后,调用类的方法‘‘‘ 24 name = input("Input your dog‘s name:\n") 25 age = input("Input your dog‘s age:\n") 26 jacksDog = dog(name,age) 27 ‘‘‘这里调用类的方法,将实例作为参数带入类的方法‘‘‘ 28 dog.sit(jacksDog) 29 dog.roll(jacksDog) 30 ‘‘‘Method one Output: 31 ************************ 32 Input your dog‘s name: 33 jack 34 Input your dog‘s age: 35 10 36 Jack is now siting. 37 Jack is now rolling 38 ************************‘‘‘ 39 40 ‘‘‘Method two 原理是一样的,但是这里直接将变量通过输入来赋值‘‘‘ 41 tomsDog = dog(input("Input your dog‘s name:\n"),input("Input your dog‘s age:\n")) 42 ‘‘‘这里直接调用实例的方法‘‘‘ 43 ‘‘‘创建了多个实例‘‘‘ 44 tomsDog.sit() 45 tomsDog.roll() 46 tomsDog.updateColor(input("what‘s your dog‘s color:\n")) 47 ‘‘‘Method two Output: 48 ************************ 49 Input your dog‘s name: 50 tom 51 Input your dog‘s age: 52 9 53 Tom is now siting. 54 Tom is now rolling 55 what‘s your dog‘s color: 56 yellow 57 Tom‘s color is yellow 58 ************************‘‘‘
时间: 2024-11-05 14:45:41