Python中用户定义的基类

问题描述 投票:-1回答:1

我正在使用python库,然后我注意到已经定义了特定的基类,并且所有其他类都从该基类派生。我的问题是,为什么在编写库时需要这样的定义和结构

class baseclass(object):
 def __init__(self):
    raise NotImplementedError("this is an abstract class")

 def __enter__(self):
    raise NotImplementedError("this is an abstract class")

 def __exit__(self, exc_type, exc_value, traceback):
    raise NotImplementedError("this is an abstract class")

class Myclass(baseclass):
  def __init__(self):
    ""

 def __enter__(self):
   ""

 def __exit__(self, exc_type, exc_value, traceback):
    ""
 def method1(self):
   pass
python-3.x inheritance abstract-class derived-class
1个回答
0
投票

抽象类通常是父类,您可以认为父类具有子类将从父类继承的类变量。抽象类取决于@Mad Physicist答案中提到的情况。如果以下任何一种情况适用于您的情况,则可以考虑使用抽象类:

您想在几个紧密相关的类之间共享代码。您期望扩展您的抽象类的类具有许多公共方法或字段,或者需要除public(例如protected和private)之外的访问修饰符。您要声明非静态或非最终字段。这使您能够定义可以访问和修改它们所属对象的状态的方法。

© www.soinside.com 2019 - 2024. All rights reserved.