【问题标题】:user defined base class in pythonpython中用户定义的基类
【发布时间】:2020-07-15 05:58:23
【问题描述】:

我正在使用 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】:

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

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

【讨论】:

  • 你的引用真的不是关于 python,听起来它指的是 Java/C++ 或类似的语言。
  • 据我了解,问题是“为什么我们在编写库时需要这样的定义和结构”。我只是想解释一下为什么我们需要这种结构。但是,你也是对的,我的回答本质上变得非常笼统。
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2012-05-28
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多