简体   繁体   English

从 Python 中的另一个 class 实例化 class

[英]instantiating a class from another class in Python

I was looking at linked list program in Python I did'nt quite understand it.我在看 Python 中的链表程序,我不太明白。

I would appreciate if you help me on it.如果您能帮助我,我将不胜感激。

Im pasting a part of code here, to simplify and understand one functionality我在这里粘贴一部分代码,以简化和理解一个功能

class node:

    def __init__(self,data,nnext=None):
        self.data = data
        self.nnext = nnext

class linkedList:
    def __init__(self):
        self.head = None

    def insertion(self,data):
        myinsertobj = node(data)

Here 1. We have created a class for a node.这里 1. 我们为一个节点创建了一个 class。 2. We created another class with a single head node. 2. 我们创建了另一个具有单个头节点的 class。 3. In second class we have written a method for inserting. 3. 在第二个 class 我们写了一个插入方法。 In the insertion() method, we are creating an object to the first class.在 insert() 方法中,我们为第一个 class 创建了一个 object。

Now what I dont understand is, how to create object for the second class ie linkedList class and how to call the insertion() Method,considering the above code only.(I don't want to use helper method yet)现在我不明白的是,如何为第二个 class 创建 object 即 linkedList class 以及如何调用 insert() 方法,只考虑上面的代码方法。

Please help me understand it, as Im new to Python and trying to learn it.请帮助我理解它,因为我是 Python 的新手并试图学习它。 The complete code is @ ==> https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python完整代码为@ ==> https://www.eduative.io/edpresso/how-to-create-a-linked-list-in-python

Also, Please suggest me few references for data structures in simple way.另外,请以简单的方式向我推荐一些数据结构的参考资料。

Given the code you posted, in order to create an object for the second class, you would call鉴于您发布的代码,为了为第二个 class 创建 object,您可以调用

obj1 = linkedList()

where obj1 is now and instance of the linked list class.其中 obj1 现在是链表 class 的实例。

To insert a node into obj1 you call the insertion method like so要将节点插入到 obj1 中,您可以像这样调用插入方法

obj1.insertion(data)

where data can be anything you want to insert.其中 data 可以是您想要插入的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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