【问题标题】:Creating new object of a class in the same class in python?在python的同一个类中创建一个类的新对象?
【发布时间】:2017-06-19 00:55:29
【问题描述】:

是否可以在自身(在 python 中)创建一个类的新对象?

为了更详细地解释这个想法,我编写了这段代码,我认为它不起作用。

新对象应该明显独立于当前对象(新属性等)

class LinkedList:

    def __init__(self):
        """ Construct an empty linked list. """
        self.first = None
        self.last = None

   def insert_before(self, new_item, next_item):
        """ Insert new_item before next_item. If next_item is None, insert
        new_item at the end of the list. """

        # First set the (two) new prev pointers (including possibly last).
        if next_item is not None:
            new_item.prev = next_item.prev
            next_item.prev = new_item
        else:
            new_item.prev = self.last
            self.last = new_item
        # Then set the (two) new next pointers (including possibly first).
        if new_item.prev is not None:
            new_item.next = next_item
            new_item.prev.next = new_item
        else:
            new_item.next = self.first
            self.first = new_item

    # assuming l1, l2 obj of class node with prev and next (attributes)
    def slice(self, l1, l2):
        curr = l1

        new = LinkedList()
        new.first = l1
        new.last = l2
        if l1.prev is not None:
           l2.prev = l1.prev
        else:
           self.first = l2.next
           self.first.prev = None

        if l2.next is not None:
           l1.next = l2.next
        else:
            self.last = l2.next
        Return new

class Node:

    def __init__(self, value):
    """ Construct an item with given value. Also have an id for each item,
    so that we can simply show pointers as ids. """

        Node.num_items += 1
        self.id = Node.num_items
        self.prev = None
        self.next = None
        self.value = value

    def __repr__(self):
    """ Item as human-readable string. In Java or C++, use a function like
    toString(). """

        return "[id = #" + str(self.id) \
           + ", prev = #" + str(0 if self.prev is None else self.prev.id) \
           + ", next = #" + str(0 if self.next is None else self.next.id) \
           + ", val = " + str(self.value) + "]"

【问题讨论】:

  • 您显示的代码确实创建了一个完全独立的test 实例。尽管该示例有点毫无意义,因为test 无论如何都没有任何属性。为什么你认为它不起作用?你打算用new做什么? (顺便说一句,你的 __init__ 有语法错误。)
  • 您的代码运行良好。你试过了吗?
  • @5gon12eder 因为我尝试了真实代码,并尝试更改属性值,但没有成功
  • 请务必发布minimal reproducible example,而不是您拥有的完整程序。花时间将您的代码缩减到尽可能小的大小,同时仍然表现出您所询问的行为。
  • 我认为它行不通...请详细解释为什么不行。

标签: python oop linked-list


【解决方案1】:

是否可以自己创建一个类的新对象(在 python 中)?

是的。完全有可能。

这是一个例子:

>>> class A:
    def __init__(self, value):
        self.value = value

    def make_a(self, value):
        return A(value)

    def __repr__(self):
        return 'A({})'.format(self.value)


>>> a = A(10)
>>> a.make_a(15)
A(15)
>>> 

现在你可能在想,“但是 A 类还没有定义。为什么 Python 不提出 NameError ?” Python 执行代码的方式。

当 Python 创建 A 类,特别是 make_a 方法时,它会看到标识符 A 正在被调用。它不知道A 是函数还是类,或者即使A已定义。但它不需要知道。

A 的确切含义是在运行时确定的。那是 Python 检查 A 是否真的定义的唯一一次。

这也是您能够编译引用未定义变量的函数的原因:

>>> def foo():
    a + b


>>> foo # Python compiled foo...
<function foo at 0x7fb5d0500f28>
>>> foo() # but we can't call it.
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    foo() # but we can't call it.
  File "<pyshell#7>", line 2, in foo
    a + b
NameError: name 'a' is not defined
>>> 

【讨论】:

  • 很高兴帮助@James。
【解决方案2】:

这看起来像一个双端队列(双端队列),并且切片操作没有正确退出。您需要修复 l1 之前和 l2 之后的项目上的 prev/next 链接。

def slice(self, l1, l2):
    new = LinkedList()
    new.first = l1
    new.last = l2
    if l1.prev:
       l1.prev.next = l2.next
    if l2.next:
       l2.next.prev = l1.prev
    l1.prev = l2.next = None
    return new

【讨论】:

  • 这确实清理了他的代码。对此表示敬意。但这似乎并没有真正回答他的主要问题:“是否有可能在自身(在python中)创建一个类的新对象?”。跨度>
  • 但我认为这会改变列表本身。切片函数应该返回想要的部分,并且真实列表将被更新。例如:list = [1, 2, 3, 4] list.slice(2,3) 返回 [2,3] 列表将是 [1,4]
  • 代码思路很好,我发现了一些问题,例如 slice(the whole list) 或者只是第一个元素 list(a,a) 。我认为如果(S)可以完成这项工作
  • @james... 我猜了 OP 所说的“切片”是什么意思。如果要保留原始列表,还需要复制所有节点以保持链接分开。我认为这适用于slice(a,a) ... 否则我的铅笔和纸原型设计失败了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2022-01-16
  • 2015-11-12
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多