1、子类和父类
子类和父类主要描述的是类之间的继承关系,即所属关系。继承 的类可在被继承的类的基础上添加格外的参数和行为,新类称为子类,扩展类;被继承的类称为基类、父类或者超类。
使用方法:
##基本格式
class Father(object): ##父类
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print('%s is eating...' %self.name)
class Son(Father): ##子类
def eat(self):
print('%s daoli eating...' %self.name)
father = Father('laolaoli',65) ##申明初始变量
son = Son('laoli',40)
son.run() ##调用
当子类和父类中有相同的方法时,会默认调用子类中的方法(对子类的对象),若要调用父类,可采取如下方法:
##调用父类中的方法
......
class Son(Father):
def eat(self):
# super(Son,self).eat() ##调用父类
# Father.eat(self) ##调用父类
print('%s daoli eating...' %self.name)
......
上述是两种方法,任选其一即可。
2、新式类和经典类
在操作类的时候,会出现同一个类被多个类所调用,或者被递归的调用。当读取的时候就有两个规则,我们将其称为新式类和经典类。新式类是以广度优先为方式进行调用的,经典类是以深度优先的方式进行调用。
对调用方法可以进行如下代码测试:
class D(object):
def test(self):
print('test in D...')
class C(D):
def test(self):
print('test in C...')
class B(D):
def test(self):
print('test in B...')
class A(B,C):
def test(self):
print('test in A...')
a = A()
a.test()
在上述程序中我们可以进行逐一调试,查看调用方式。值得注意的是object就是用来表示父类的调用方式。在python2中默认是经典类的调用(若想使用新式类调用,可在父类中添加关键字object),在python3中则默认是新式类调用。
3、类内的关系变量
有时为了对程序进行检测,我们常采用类内部的变量对其进行检测,基本定义方式为‘--’+名称:
##声明
class Student(object):
def __init__(self,name,age):
self.name = name ##外部名称
self.__age = age ##内部名称
def __get_info(self):
doing...
一般情况下,内部变量和内部方式均不可被外部所使用,除非使用特定方式。
##使用内部变量
student1._Student__get_info()
##student1 对像名称
##Student 类名称
##__get_info 类内的内部变量
4、类的“并发”
当不同的类在定义时,不同类下的名称为同一名称,在定义对象使用时,仍然可以使用,这就为子类和父类的定义,打下了基础。
class Student():
def name(self):
doing...
class Chinese():
def name(self):
doing...
class Math():
def name(self):
doing...
student1 = Student()
student2 = Chinese()
student3 = Math()
student1.name()
student2.name()
student3.name()
上述示例中,3个对象调用不同的用户,用户所执行的行为是不同的。
5、示例
![](https://img-blog.csdnimg.cn/20200426095018936.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDU2MjI0,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20200426095204659.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDU2MjI0,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20200426104312401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDU2MjI0,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20200426105252178.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDU2MjI0,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20200426105343684.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMDU2MjI0,size_16,color_FFFFFF,t_70)