Python——一个简单的类的创建和应用

时间:2024-01-12 16:51:44

1、创建类,设置属性和给属性设定默认值,设置方法并访问类的属性;

2、利用类创建多个实例,以及调用类的方法的两种办法;

3、设置更新属性的函数,并更新实例的属性。

 class dog(object):
"""创建小狗类""" def __init__(self, name, age):
"""初始化参数,Python创建实例时,自动传入实参self,指向实例本身,以便访问属性和方法"""
self.name = name
self.age = age
'''给属性指定默认值'''
self.color = 'white' def sit(self):
'''访问类的属性'''
print(self.name.title() + ' is now siting.') def roll(self):
print(self.name.title()+ ' is now rolling') '''通过方法修改属性的值'''
def updateColor(self,color):
self.color = str(color)
print(self.name.title()+ "'s color is " + str(color)) '''Method one 通过先给参数赋值,再带入到类形参中,创建一个实例后,调用类的方法'''
name = input("Input your dog's name:\n")
age = input("Input your dog's age:\n")
jacksDog = dog(name,age)
'''这里调用类的方法,将实例作为参数带入类的方法'''
dog.sit(jacksDog)
dog.roll(jacksDog)
'''Method one Output:
************************
Input your dog's name:
jack
Input your dog's age:
10
Jack is now siting.
Jack is now rolling
************************''' '''Method two 原理是一样的,但是这里直接将变量通过输入来赋值'''
tomsDog = dog(input("Input your dog's name:\n"),input("Input your dog's age:\n"))
'''这里直接调用实例的方法'''
'''创建了多个实例'''
tomsDog.sit()
tomsDog.roll()
tomsDog.updateColor(input("what's your dog's color:\n"))
'''Method two Output:
************************
Input your dog's name:
tom
Input your dog's age:
9
Tom is now siting.
Tom is now rolling
what's your dog's color:
yellow
Tom's color is yellow
************************'''