在python中从父类文件调用子类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25062114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:40:41  来源:igfitidea点击:

calling child class method from parent class file in python

pythonclassinheritanceparent

提问by Jagadeesh N M

parent.py:

parent.py

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

child.py:

child.py

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

Is there anyway to call methodb()in parent.py?

反正是有电话methodb()parent.py

回答by TheSoundDefense

You could use the function anywhere so long as it was attached to an object, which it appears to be from your sample. If you have a Bobject, then you can use its methodb()function from absolutely anywhere.

您可以在任何地方使用该功能,只要它附加到一个 object,它似乎来自您的示例。如果你有一个B对象,那么你可以methodb()在任何地方使用它的功能。

parent.py:

parent.py:

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

def aFoo(obj):
  obj.methodb()

child.py

child.py

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

You can see how this works after you import:

导入后,您可以看到它是如何工作的:

>>> from parent import aFoo
>>> from child import B
>>> obj = B()
>>> aFoo(obj)
am in methodb

Granted, you will not be able to create a new Bobject from inside parent.py, but you will still be able to use its methods if it's passed in to a function in parent.pysomehow.

当然,您将无法B从 inside创建新对象parent.py,但如果以parent.py某种方式将其传递给函数,您仍然可以使用其方法。

回答by dano

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

这样做只有在A是一个抽象基类时才有意义,这意味着它A只能用作其他类的基类,而不是直接实例化。如果是这种情况,您将methodB在 A 类上定义,但不实现它:

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")

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

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

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

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

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")

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

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

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

The same would happen if you tried instantiating A.

如果您尝试实例化A.

回答by Alexey

You can do something like this:

你可以这样做:

class A():
    def foo(self):
        self.testb()

class B(A):
    def testb(self):
        print('lol, it works')
b = B()
b.foo()

Which would return this of course:

这当然会返回这个:

lol, it works

Note, that in fact there is no call from parent, there is just call of function foofrom instance of child class, this instance has inherited foofrom parent, i.e. this is impossible:

注意,实际上没有来自父foo类的调用,只有来自子类实例的函数调用,这个实例是foo从父类继承的,即这是不可能的:

a=A()
a.foo()

will produce: AttributeError: A instance has no attribute 'testb'

将产生: AttributeError: A instance has no attribute 'testb'

because

因为

>>> dir(A)
['__doc__', '__module__', 'foo']
>>> dir(B)
['__doc__', '__module__', 'foo', 'testb']

What I've wanted to show that you can create instance of child class, and it will have all methods and parameters from both parent and it's own classes.

我想展示的是您可以创建子类的实例,并且它将拥有来自父类和它自己的类的所有方法和参数。

回答by grepit

There are three approaches/ways to do this ! but I highly recommend to use the approach #3 because composition/decoupling has certain benefits in terms of design pattern. (GOF)

有三种方法/方法可以做到这一点!但我强烈建议使用方法#3,因为组合/解耦在设计模式方面有一定的好处。(GOF

## approach 1 inheritance 
class A():
    def methodA(self):
        print("in methodA")
    def call_mehtodB(self):
        self.methodb()

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

b=B()
b.call_mehtodB()


## approach 2 using abstract method still class highly coupled
from abc import ABC, abstractmethod
class A(ABC):
    def methodA(self):
        print("in methodA")
    @abstractmethod    
    def methodb(self):
       pass

class B(A):

    def methodb(self):
        print("am in methodb")

b=B()
b.methodb()

#approach 3 the recommended way ! Composition 

class A():
    def __init__(self, message):
        self.message=message

    def methodA(self):
        print(self.message)

class B():
    def __init__(self,messageB, messageA):
        self.message=messageB
        self.a=A(messageA)

    def methodb(self):
        print(self.message)

    def methodA(self):
        print(self.a.message)

b=B("am in methodb", "am in methodA")
b.methodb()
b.methodA()