Python和新实例

时间:2012-10-10 00:10:38

标签: python

虽然我熟悉其他编程语言,但我很难理解我在python中的代码,以及为什么在重新分配类时我的类属性不会重置...例如。我在通知类中有一个方法

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

正如您所看到的,这将遍历每个服务(所以请记住我有3个xbmc)

所以以xbmc为例,方法是

def xbmc(self, host):
  x = Xbmc(host)
  x.notify(self.title, self.message)

在其他语言下,如果我再次分配x,它将是一个全新的对象,但这似乎不是python的情况......

我会从我的xbmc类中删除片段来解释这个问题。

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

现在代码在那里,当我发起我的发送通知。输出显示:

[<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

很明显,当我追加主机时,它实际上从来不是一个新实例,但总是追加已经存在的东西......我假设x = Class()会启动一个新实例?如果我做了

self.hosts = [host]
然后显然我没有得到不良影响,但是也很好知道为什么我最初的approch不起作用或如何克服它。我们需要重置方法吗?或者实际上是否有办法在课堂上创建新实例?或者我的代码有问题吗?感谢....

2 个答案:

答案 0 :(得分:1)

问题

问题是由于类属性hosts是可变的(列表)引起的,因此附加到它将影响每个实例。

解决方案

解决方案是将class属性更改为instance属性:

class Xbmc:
    # <--- (no more "hosts" here)
    def __init__(self, host = None):
        self.hosts = []  # <--- we are initializing "hosts" property here now
        self.setHosts(host)
        self.server = Hosts().getHostsByService('xbmcserver')
    # and so on...

答案 1 :(得分:0)

class Xbmc:
  hosts = []
  def __init__(self, host = None):
    self.setHosts(host)
    self.server = Hosts().getHostsByService('xbmcserver')

应该是

class Xbmc:
  def __init__(self, host = None):
    self.hosts = []
    self.setHosts(host)
    self.server = Hosts().getHostsByService('xbmcserver')

第一个版本创建了一个在所有Xbmc实例之间共享的列表。第二个为每个创建一个列表。