Inheritance vs class instance in python module import

后端 未结 2 987
盖世英雄少女心
盖世英雄少女心 2021-01-13 20:15

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

Consider the following code:

import mymodule

class MyClass:
             


        
相关标签:
2条回答
  • 2021-01-13 20:31

    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.

    0 讨论(0)
  • 2021-01-13 20:51

    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?

    0 讨论(0)
提交回复
热议问题