python 子类调用父类的构造函数实例

当子类继承父类后,需要调用父类的方法和属性时,需要调用父类的初始化函数。

class A(object):
  def __init__(self):
    self.nameaa = 'aa'
  def funca(self):
    print('function a %s' % self.nameaa)
    
class B(A):
  def __init__(self):
    self.namebb = 'bb'
   def funcb(self):
    print('function b %s' % self.namebb)
    
b = B()
print(b.namebb)
b.funcb()
print(b.nameaa)
b.funca()

在子类中重写了构造函数,但新的构造函数没有初始化父类,当没有初始化父类的构造函数时,就会报错。

(2)使用super函数

class A(object):
  def __init__(self):
    self.nameaa = 'aa'
  def funca(self):
    print('function a %s' % self.nameaa)
    
class B(A):
  def __init__(self):
    self.namebb = 'bb'
    super(B,self).__init__()
  def funcb(self):
    print('function b %s' % self.namebb)
    
b = B()
print(b.namebb)
b.funcb()
print(b.nameaa)
b.funca()

补充知识:python3 和python2 调用父类构造方法写法区别

1. python3 和python2 调用父类构造方法写法区别

前一段时间,把之前的一个项目迁移到python3

发现了很多不同的地方.我这里简单说明了,构造方法的不同 之后可能会继续更新不同. 主要针对项目迁移进行总结,反思. 这里就当做笔记.

python3 代码 调用父类的构造方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: frank.chang@shoufuyou.com
@file: py2topy3.py
@time: 2018/7/7 上午7:09
## python3 代码 
 
"""
 
import threading
import queue
 
_sentinel = object()
 
 
class Consumer(threading.Thread):
  """
  消费者线程类
  """
 
  def __init__(self, name, queue):
    super().__init__(name=name)
    self.queue = queue
 
  def run(self):
    while True:
      values = self.queue.get(timeout=None)
 
      if values is _sentinel:
        self.queue.put(values)
        break
      ##process values
      ##xxx
      print('consume is consuming data {}'.format(values))
 
    print("{} finished".format(self.getName()))
 
 
if __name__ == '__main__':
  q = queue.Queue()
  concumser = Consumer('consumer', q)
 
  print(concumser)

2 python2.7 调用父类的构造方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: frank.chang@shoufuyou.com
@file: 3.py
@time: 2018/7/7 上午7:05
"""
 
import Queue
import threading
 
# 哨兵
_sentinel = object()
 
 
class Consumer(threading.Thread):
  """
  消费者线程类
  """
 
  def __init__(self, name, queue):
    super(Consumer, self).__init__(name=name)
    self.queue = queue
 
  def run(self):
    while True:
      values = self.queue.get(timeout=None)
 
      if values is _sentinel:
        self.queue.put(values)
        break
      ##process values
      ##xxx
      print('consume is consuming data {}'.format(values))
 
    print("{} finished".format(self.getName()))
 
 
if __name__ == '__main__':
  q = Queue.Queue()
  concumser = Consumer('consumer', q)
  print(concumser)

区别

主要区别是 super 的变化,

python3 中直接 super().init() 中 super 不需要传递任何参数,直接可以调用父类的构造方法

python2 中 super(Consumer, self).init(), 需要传两个参数一个是类名, 一个是self. 这样比较麻烦,很容易混淆. 但是python3 这里处理的比较好了.

可以看下这个文档 https://docs.python.org/3/library/functions.html#super

顺便提一下, python2 和python3 中 quque 名称换了,python3 用的是小写 作为模块名称.

以上这篇python 子类调用父类的构造函数实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。