从python中的父类文件调用子类方法 [英] calling child class method from parent class file in python

查看:1942
本文介绍了从python中的父类文件调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

parent.py

class A(object):
    def methodA(self):
        print("in methodA")

来自父导入的 child.py

from parent import A
class B(A):
    def methodb(self):
        print("am in methodb")

无论如何在 parent.py 中调用 methodb()

推荐答案

只有当 A 是一个抽象基类时才这样做,这意味着 A 仅用作其他类的基础,不直接实例化。如果是这种情况,你可以在A类上定义 methodB ,但保持未实现:

Doing this would only make sense if A is an abstract base class, meaning that A is only meant to be used as a base for other classes, not instantiated directly. If that were the case, you would define methodB on class A, but leave it unimplemented:

class A(object):
    def methodA(self):
        print("in methodA")

    def methodB(self):
        raise NotImplementedError("Must override methodB")


from parent import A
class B(A):
    def methodB(self):
        print("am in methodB")

这不是绝对必要的。如果您未在 A 中的任何位置声明 methodB ,并实例化 B ,你仍然可以从 methodA 的主体调用 methodB ,但这是一个不好的做法;目前尚不清楚 methodA 应该来自何处,或者子类需要覆盖它。

This isn't strictly necessary. If you don't declare methodB anywhere in A, and instantiate B, you'd still be able to call methodB from the body of methodA, but it's a bad practice; it's not clear where methodA is supposed to come from, or that child classes need to override it.

如果你想要更正式,你可以使用Python abc 模块将A声明为抽象基类。

If you want to be more formal, you can use the Python abc module to declare A as an abstract base class.

from abc import ABCMeta, abstractmethod

class A(object):
 __metaclass__ = ABCMeta

    def methodA(self):
        print("in methodA")

    @abstractmethod
    def methodB(self):
        raise NotImplementedError("Must override methodB")

使用它实际上会阻止你实例化 A 或任何继承自 A 的类而不会覆盖的methodB 。例如,如果B看起来像这样:

Using this will actually prevent you from instantiating A or any class that inherits from A without overriding methodB. For example, if B looked like this:

class B(A):
   pass

尝试实例化它时会出错:

You'd get an error trying to instantiate it:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class B with abstract methods methodB

同样会发生如果您尝试实例化 A

The same would happen if you tried instantiating A.

这篇关于从python中的父类文件调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆