python模块导入中的继承vs类实例 [英] Inheritance vs class instance in python module import

查看:174
本文介绍了python模块导入中的继承vs类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这没有道理,我不是一个经验丰富的程序员.

Apologies if this doesn't make sense, i'm not much of an experienced programmer.

考虑以下代码:

import mymodule

class MyClass:
    def __init__(self):
        self.classInstance = myModule.classInstance()

然后...

from mymodule import classInstance

class MyClass(classInstance):
    def __init__(self):
        pass

如果我只想在MyClass中使用一个classInstance,可以从模块中导入特定的类并让MyClass继承该类吗?

If I just wanted to use the one classInstance in MyClass, is it ok to import the specific class from the module and have MyClass inherit this class ?

在确定这两种方法时是否有最佳实践,或者我应该考虑的事情?

Are there any best practices, or things I should be thinking about when deciding between these two methods ?

非常感谢

推荐答案

允许我提出一个不同的示例.

Allow me to propose a different example.

想象一下,有一个Vector类. 现在您要一个类Point.可以用向量定义点,但也许它具有向量没有的其他功能. 在这种情况下,您可以从Vector得出Point.

Imagine to have the class Vector. Now you want a class Point. Point can be defined with a vector but maybe it has other extra functionalities that Vector doesn't have. In this case you derive Point from Vector.

现在,您需要一个Line类. Line不是以上任何一个类的专业化,因此您可能不想从任何这些类派生它. 但是Line使用点.在这种情况下,您可能想以这种方式启动Line类:

Now you need a Line class. A Line is not a specialisation of any of the above classes so probably you don't want to derive it from any of them. However Line uses points. In this case you might want to start you Line class this way:

class Line(object):
    def __init__(self):
        self.point1 = Point()
        self.point2 = Point()

要点如下:

class Point(Vector):
    def __init__(self):
        Vector.__init__(self)

答案确实是:取决于您需要做什么,但是当您清楚地知道要编写什么代码时,要在子类化与不子类化之间进行选择就变得显而易见了.

So the answer is really: Depends what you need to do, but when you have a clear idea of what you are coding, than choosing between sub-classing or not becomes obvious.

我希望它能帮上忙.

这篇关于python模块导入中的继承vs类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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