python中的类,对象,实例,继承,多态
------------恢复内容开始------------
类 (通俗来讲是 属性和方法的集合)
用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。
对象,即为类的实例,对象可调用类的属性和方法
类的定义,需要以大写开头来定义类的名字 class Test
class Test():#定义类 首字母大写 a = 12345 #类的属性 def fun(self):#类的方法 print('我是类里面的方法') T = Test()#实例一个类的对象 print(T.a) #对象调用类的属性 T.fun() #对象调用类的方法
继承,简化代码,继承的顺序是从左至右,父类的私有方法无法被继承
class Test():#定义类 首字母大写 a = 12345 #类的属性 def fun(self):#类的方法 print('我是类里面的方法') T = Test()#实例一个类的对象 print(T.a) #对象调用类的属性 T.fun() #对象调用类的方法 #类的继承 class Test_sun(Test):#继承了Test类 b = 67890 def fun1(self): print('我是子类的方法') T_sun = Test_sun()#实例一个子类的对象 print(T_sun.a)#调用父类的属性 T_sun.fun1()#调用子类的方法
多态,
#多态:同一种事物的多种形态, class Animal: def run(self): print('散步,狗刨,爬') class People(Animal): def run(self): print('散步') class Dog(Animal): def run(self): print('狗刨') class Tortoise(Animal): def run(self): print('爬') peo = People() dog = Dog() tortoise = Tortoise() peo.run() dog.run() tortoise.run()
------------恢复内容结束------------
类 (通俗来讲是 属性和方法的集合)
用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。
对象,即为类的实例,对象可调用类的属性和方法
类的定义,需要以大写开头来定义类的名字 class Test
class Test():#定义类 首字母大写 a = 12345 #类的属性 def fun(self):#类的方法 print('我是类里面的方法') T = Test()#实例一个类的对象 print(T.a) #对象调用类的属性 T.fun() #对象调用类的方法
继承,
class Test():#定义类 首字母大写 a = 12345 #类的属性 def fun(self):#类的方法 print('我是类里面的方法') T = Test()#实例一个类的对象 print(T.a) #对象调用类的属性 T.fun() #对象调用类的方法 #类的继承 class Test_sun(Test):#继承了Test类 b = 67890 def fun1(self): print('我是子类的方法') T_sun = Test_sun()#实例一个子类的对象 print(T_sun.a)#调用父类的属性 T_sun.fun1()#调用子类的方法
多态,
#多态:同一种事物的多种形态, class Animal: def run(self): print('散步,走,爬') class People(Animal): def run(self): print('散步') class Dog(Animal): def run(self): print('狗刨') class Tortoise(Animal): def run(self): print('爬') peo = People() dog = Dog() tortoise = Tortoise() peo.run() dog.run() tortoise.run()