在python中的类之间传递变量

时间:2014-07-29 09:52:39

标签: 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的值传递给其他类/函数

更新:已更正。问题不是使用自我而不是传递它们(抱歉还在学习并且是python的新手)。


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

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

        def delete(self):
           print 'Before Delete: ',self.vmitems
           self.vmitems.update(vmid='30')
           self.vmitems.update(url='newurl')
           return self.vmitems

        def shownow(self):
            print 'After Delete: ',self.vmitems

1 个答案:

答案 0 :(得分:1)

我建议您在代码中使用不同的方法,但需要进行一些更改,但我认为使用起来会更容易。

如果你的课程内有方法,请使用self

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

    def some_func():
        print self._vmitems 

如果您希望其他类可用,我会使用@property

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

    @property
    def get_vmitems(self):
        print("Getting vmitems")
        return self._vmitems