Inheritance vs class instance in python module imp

2019-02-19 05:10发布

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

Consider the following code:

import mymodule

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

and then ......

from mymodule import classInstance

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

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 ?

Many thanks

2条回答
在下西门庆
2楼-- · 2019-02-19 05:19

Allow me to propose a different example.

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.

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

Where point will be something like this:

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.

I hope it helped.

查看更多
该账号已被封号
3楼-- · 2019-02-19 05:24

You make it sound like you're trying to "choose between" those two approaches, but they do completely different things. The second one defines a class that inherits from a class (confusingly) called classInstance. The first one defines a class called MyClass (not inheriting from anything except the base obect type) that has an instance variable called self.classInstance, which happens to be set to an instance of the classInstance class.

Why are you naming your class classInstance?

查看更多
登录 后发表回答