day9 Override the method of the parent class

一、class Conn1(object):

    def conn(self,host,passwd):

      print(host,passwd)

inherited conn1

class  Conn2(conn1):

    def conn(self):

       print('haha')

c=Conn2()

c.conn()

The print result is: Haha, override the method of the parent class

 

Second, save the code, do not have to re-write the code

class Conn1(object):

base class

    def __init__(self,host,passwd,port):

        self.host=host

        self.passwd=passwd

        self.port=port

 

class  Conn2(Conn1):

    def __init__(self,host,passwd,port,username,db,chartset='utf8')):

       Manually calling the function of the parent class is equivalent to calling, self.host, self.passwd, self.port

       Conn1.conn(self,host,passwd,port)

        Another way of writing, the effect is the same as above, super will automatically find the parent class according to this class

        super(Conn2,self).__init__(host,passwd,port)

        self.username=username

        self.db=db

        self.chartset=chartset

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325258199&siteId=291194637