passing variables between classes in python
我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 |
我想知道是否有人能告诉我如何将EDOCX1的值(0)传递给其他类/函数
更新:已更正。问题是没有使用self,也没有传递它们(抱歉,仍然在学习,对python来说是新手)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 2 3 4 5 6 | class VM(): def __init__(self): self._vmitems = {'url' : 'stuff','vmid' : '10'} def some_func(): print self._vmitems |
如果希望它对其他类可用,我将使用@property:
1 2 3 4 5 6 7 8 | class VM(): def __init__(self): self._vmitems = {'url' : 'stuff','vmid' : '10'} @property def get_vmitems(self): print("Getting vmitems") return self._vmitems |