在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)。
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 个回答
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