簡體   English   中英

如何在運行時使用python動態創建新的類實例?

[英]How to create new class instances dynamically at runtime in python?

我正在嘗試解決這個問題:

想象一下(文字)一疊盤子。 如果堆棧太高,可能會傾倒。 因此,在現實生活中,當前一個堆棧超過某個閾值時,我們可能會啟動一個新的堆棧。 實現一個模仿它的數據結構SetOfStacks。 SetOf-Stacks應該由幾個堆棧組成,並且一旦前一個堆棧超過容量,就應該創建一個新的堆棧。 SetOfStacks.push()和SetOfStacks.pop()的行為應與單個堆棧相同(也就是說,pop()返回的值應與僅有單個堆棧時的值相同)。 獎勵:實現一個函數popAt(int index),該函數在特定的子堆棧上執行彈出操作。

所以我寫了代碼:

#!/bin/env python

from types import *

class Stack:

    def __init__(self):
        self.items = []
        self.capacity = 3
        self.stackscount = 0

    def create(self):
        id = self.stackscount + 1
        id = str(id) + "_stack"
        # How to create a new instance of Stack class at runtime ?
        # the __init__ must be run too.

    def push(self, item):
        if self.size() <= self.capacity:
            self.items.append(item)
        else:
            self.create()

    def pop(self):
        return self.items.pop()

    def popAt(self):
        pass

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

s = Stack()
s.push(10)

如何在運行時動態創建新的s類型對象? 我在互聯網上搜索,發現使用new.instance或new.classobj是解決方案,但是當我這樣做時,我的新對象似乎沒有__init__函數中的items 在python3中, type()似乎是答案,但是該文檔沒有任何示例。

您通過引用“類型對象”感到困惑。 在Python中,這意味着類本身,而不是其實例。

要創建新的Stack對象,只需執行您已經在做的事情:調用Stack類。 您可以將它們附加到列表中:

stacks = [Stack() for _ in range(5)]

但是,正如jon所指出的那樣,由於您尚未定義SetOfStacks類,因此無法解決您的問題。

type()函數確實是您要尋找的。 可以在這里找到文檔: https : //docs.python.org/2/library/functions.html#type

您可以這樣稱呼它:

# Bases is a tuple of parent classes to inherit
bases = Stack,

# Dict contains extra properties for the class, for example if you want to add a class variable or function
dict_ = {}

# Construct the class
YourClass = type('YourClass', bases, dict_)

# Create an instance of the class
your_instance = YourClass()

看來您只是在查看實例創建:

class Stack(object):

    def create(self):
        id = self.stackscount + 1
        id = str(id) + "_stack"
        # How to create a new instance of Stack class at runtime ?
        # the __init__ must be run too.
        stack = Stack()

您可以簡單地使用父子關系:當堆棧已滿時,它將創建一個子級並委托下一次推送。 它可能導致:

class Stack:

    def __init__(self, parent = None, id=None):
        self.stackscount = 0
        self.capacity = 3
        self.items = []
        self.parent = parent
        self.id = id
        self.child = None

    def create(self):
        id = self.stackscount + 1
        id = str(id) + "_stack"
        return Stack(self, id)

    def push(self, item):
        if self.size() <= self.capacity:
            self.items.append(item)
        else:
            if self.child is None:
                self.child = self.create()
            self.child.push(item)

    def pop(self):
        if self.child is not None:
            item = self.child.pop()
            if len(self.child.items) == 0:
                self.child = None
        else:
            item = self.items.pop()
        return item

    def popAt(self):
        pass

    def peek(self):
        if self.child is not None:
            item = self.child.peek()
        else:
            item = self.items[len(self.items)-1]
        return item

    def size(self):
        l = len(self.items)
        if self.child is not None:
            l += self.child.size()
        return l

s = Stack()
s.push(10)

popAt仍然有待實現,但我對其進行了測試,它在推入和清空時正確創建了新堆棧,並在彈出時將其刪除。

popAt的實現將需要對當前的pop實現進行一些改進,以允許刪除中間堆棧:

def pop(self):
    if self.child is not None:
        item = self.child.pop()
        if len(self.child.items) == 0:
            self.child = self.child.child
            if self.child is not None:
                self.child.parent = self
    else:
        item = self.items.pop()
    return item

def popAt(self, stacknumber):
    s = self
    for i in range(stacknumber):
        s = s.child
        if s is None:
            return None
    if len(s.items) == 0:
        return None
    item = s.items.pop()
    if len(s.items) == 0 and s.parent is not None:
        s.parent.child = s.child
        if s.child is not None:
            s.child.parent = s.parent
    return item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM