简体   繁体   中英

Inheritance vs class instance in python module import

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

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.

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM