【使用报错提示】NotImplementedError进行子/父类编程

  • 写作动机:在学习PyTorch时,有个 “_check_input_dim” 函数,该函数在子类中有,在父类 “_BatchNorm” 的forward中只有类似声明一样的self._check_input_dim(input)。 这时候在父类中无法转到定义,于是有此文。

  • 以下是正文

NotImplementedError用在子父类编程中。首先给出我们的实例代码,然后进行分析。

""" 
 Test NotImplementedError
"""

# 基类
class BaseClass():

    def _get_print1(self):
        raise NotImplementedError("Hello small MM! ")


class Class1(BaseClass):
	# 试一下把下面两行改为 pass?
    def _get_print1(self):
        print("Wao Big MM! ")

gg = Class1()
gg._get_print1() # 只有在调用该函数的时候才会执行检查!
  • 分析:
    这个代码是可以正常执行的。因为子类中定义了 _get_print1(self) 函数,而如果子类中没有定义该函数,就会激活父类中的Error,可以在多个子类该函数不同功能时使用,类似于C++的重载。
发布了18 篇原创文章 · 获赞 0 · 访问量 477

猜你喜欢

转载自blog.csdn.net/m0_38139098/article/details/104623136