Although i’m familiar with other programming languages, I’m struggling to understand my code in python and why my class properties aren’t reset when i reassign the class… eg. I have a method in a notify class
def send(self):
for service in self.hosts:
# func = getattr(self, service)
for host in self.hosts[service]:
try:
if service == 'xbmc':
self.xbmc(host)
elif service == 'growl':
self.growl(host)
elif service == 'prowl':
self.prowl(host)
except:
print "Cound't connect " + host.find('ip').text + " For " + service
As you can see, this will iterate through each service (so keep in mind I have 3 xbmc’s)
so take xbmc for an example, the method is
def xbmc(self, host):
x = Xbmc(host)
x.notify(self.title, self.message)
under other languages, if i would assign x again, it would be a completely new fresh object, but this doesnt seem to be the case with python…
I will place snippets off my xbmc class to explain the issue.
class Xbmc:
hosts = []
def __init__(self, host = None):
self.setHosts(host)
self.server = Hosts().getHostsByService('xbmcserver')
def setHosts(self, host = None):
...alot of elif...
elif type(host).__name__ == 'Element': # this code is the one that is in effect from my notify class
self.hosts.append(host)
...more elif...
print self.hosts # for debugging
now that the code is there, when i initiate my notify to send. the output shows:
[<Element 'host' at 0x7fdda19d0d10>]
XBMC 192.168.1.10 Failed To Connect
[<Element 'host' at 0x7fdda19d0d10>, <Element 'host' at 0x7fdda1955090>]
XBMC 192.168.1.10 Failed To Connect
XBMC 192.168.1.20 Failed To Connect
[<Element 'host' at 0x7fdda19d0d10>, <Element 'host' at 0x7fdda1955090>, <Element 'host' at 0x7fdda19553d0>]
XBMC 192.168.1.10 Failed To Connect
XBMC 192.168.1.20 Failed To Connect
XBMC 192.168.1.21 Failed To Connect
its clear that when i append the host, that its never actually a new instance but always appends to what was already there… I assumed x = Class() would initiate a New Instance? if i do
self.hosts = [host]
then obviously i dont get the undesired effect, but it would be good too know why my initial approch doesnt work or how to overcome it. Do we need a reset method? or is there actually a way to create a new instance off a class? or is there something wrong with my code? thanks….
Problem
The problem is caused, because the class property
hostsis mutable (list), so appending to it will influence every instance.Solution
The solution is to change the class property into instance property: