"""
#类名一般首字母大写
class Name():
def __init__(self,one,two):
#初始化属性
self.one = one
self.two = two
self.three = 0 #未传值,定义时必须初始化
def 方法一(self):
函数体
def 方法二(self):
函数体
"""#创建一个小狗类classDog():def__init__(self,name,age):
self.name = name
self.age = age
self.sex ='gong'definformation(self):"""输出小狗信息"""print("My dog's name is "+ self.name.title()+", it's age is "+str(self.age)+", it's sex is "+ self.sex)defsit(self):"""模拟小狗坐下"""print(self.name.title()+' is now sitting')defroll_over(self):"""模拟小狗打滚"""print(self.name.title()+' rolled over')defupdate_age(self,age):
self.age = age
类的使用
#创建一个小狗实例
my_dog = Dog('jim',8)#必须初始化_init_()方法#调用值print("My dog's name is "+ my_dog.name.title())#调用方法
my_dog.information()
my_dog.sit()
my_dog.roll_over()
修改类中属性值
#修改类中属性值#1.直接修改
my_dog = Dog('jim',5)print(my_dog.name.title()+" is "+str(my_dog.age))#Jim is 5
my_dog.age +=1print(my_dog.name.title()+" is "+str(my_dog.age))#Jim is 6#2.通过方法修改属性的值
my_dog.update_age(8)print(my_dog.name.title()+" is "+str(my_dog.age))#Jim is 8
创建子类
classDog_son(Dog):def__init__(self,name,age,color):super().__init__(name,age)
self.color = color#加一个color属性#加一个方法defcolor_print(self):print("My dog's color is "+ self.color)
子类调用方法
dog_son = Dog_son('jim',4,'yellow')#调用继承的父类方法
dog_son.information()#调用子类新写的方法
dog_son.color_print()# My dog's name is Jim, it's age is 4, it's sex is gong# My dog's color is yellow
子类重写父类方法
#子类重写父类方法classDog_son(Dog):def__init__(self,name,age,color):super().__init__(name,age)
self.color = color
defcolor_print(self):print("My dog's color is "+ self.color)definformation(self):print("change the 父类方法")
dog_son = Dog_son('jim',4,'yellow')#掉用修改后的方法
dog_son.information()#change the 父类方法
将实例用作属性
#创建一个类,作为属性classArea():def__init__(self,area):
self.area = area
defarea_print(self):print("this dog is from "+ self.area)#创建一个Dog子类classDog_son(Dog):def__init__(self,name,age):super().__init__(name,age)
self.areatry = Area('hunan')#将Area实例作为属性#调用area_print()方法
dog_son = Dog_son('jim',4)
dog_son.areatry.area_print()