在python中在类之间传递变量

2024-10-03 19:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

class VM():
    def __init__(self):
        global vmitems,vmappid
        vmitems = {'url' : 'stuff','vmid' : '10'}

    def create(self, **vmitems):
           appurl = vmitems.get('url')
           vmappid   = vmitems.get('vmid')
           vmitems.update(vmid=vmappid)
           vmitems.update(url=appurl)
           print 'New URL: '+appurl
           print 'New ID: '+vmappid
           print 'NEW LIST: ',vmitems
           return vmitems

    def delete(self, **vmitems):
           appurl = vmitems.get('url')
           vmappid   = vmitems.get('vmid')
           print 'do stuff'

action = VM()
action.create(url='https://www.google.com', vmid='20')
action.delete(url='urlhere',vmid='20')
print 'New List: ',vmitems

我想知道是否有人能告诉我如何将vmitems的值传递给其他类/函数

更新:已更正。问题是没有使用self,也没有将它们传递出去(很抱歉,仍然是python的初学者)。在

^{pr2}$

Tags: selfurlnewgetdefcreatevmupdate
1条回答
网友
1楼 · 发布于 2024-10-03 19:32:51

我建议一种不同的方法,然后你在你的代码中使用它将需要一些改变,但我认为它将更容易使用。在

{{cd1>在类中使用方法:

class VM():
    def __init__(self):
        self._vmitems = {'url' : 'stuff','vmid' : '10'}

    def some_func():
        print self._vmitems 

如果您希望它对其他类可用,我将使用@property

^{pr2}$

相关问题 更多 >