Python类TypeError:迭代非序列

时间:2014-07-23 17:43:31

标签: python class

我在file1.py

中有以下课程
class api:
  def server(self):
    DEFAULT_SERVER = socket.gethostname()
    try:
      SATELLITE_SERVER = raw_input('Enter RedHat Satellite Server Name [%s]: ' % DEFAULT_SERVER)
    except KeyboardInterrupt:
      print ""
      sys.exit(1)
    if not SATELLITE_SERVER:
      SATELLITE_SERVER = DEFAULT_SERVER
    try:
      SATELLITE_URL = 'http://' + SATELLITE_SERVER + '/rpc/api'
      CLIENT = xmlrpclib.Server(SATELLITE_URL, verbose=0)
      print "Welcome to RedHat Satellite Server %s" % CLIENT.api.systemVersion()
    except socket.error, e:
      print "Incorrect Server Name -", e
      sys.exit(1)
    return CLIENT

  def username(self):
    DEFAULT_LOGIN = getpass.getuser()
    try:
      SATELLITE_LOGIN = raw_input("Enter RedHat Satellite Login Name [%s]: " % DEFAULT_LOGIN)
    except KeyboardInterrupt:
      print ""
      sys.exit(1)
    if not SATELLITE_LOGIN:
      SATELLITE_LOGIN = DEFAULT_LOGIN
    return SATELLITE_LOGIN

  def password(self):
    try:
      SATELLITE_PASSWORD = getpass.getpass("Enter Your Password: ")
    except KeyboardInterrupt:
      print ""
      sys.exit(1)
    if not SATELLITE_PASSWORD:
      self.password()
    return SATELLITE_PASSWORD

  def __init__(self):
    CLIENT = self.server()
    SATELLITE_LOGIN = self.username()
    SATELLITE_PASSWORD = self.password()
    KEY = CLIENT.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)

  def __new__(self):
    return (self.KEY, self.CLIENT)

我在file2.py,

中调用此类
KEY, CLIENT = file1.api()
print KEY
print CLIENT

当我执行file2.py时,我收到错误

Traceback (most recent call last):
  File "./test.py", line 24, in <module>
    KEY, CLIENT = satelliteapi.api()
TypeError: iteration over non-sequence

我不确定我做错了什么,可能是在重新调整类中的值,可能 new 在这种情况下不是正确的返回方式。请帮忙。

1 个答案:

答案 0 :(得分:1)

基本上,覆盖__new__not你应该做的事情。如果您只想创建它以便轻松解压KEYCLIENT值,则可以执行以下操作:

class api(object):
....
def __iter__(self):
    return (value for value in (self.KEY, self.CLIENT))

__iter__是一种特殊方法,用于定义是否可以迭代一个类。它会返回iterator个实例(在本例中为generator),可用作“序列”。对象的表示。 This question对该主题有一个很好的解释。

如果你想让它更加明确,你可以这样做:

class api(object):
....
def get_key_and_client(self):
    return self.KEY, self.CLIENT
def __iter__(self):
    return (value for value in self.get_key_and_client())

这使您可以在不需要实际使用迭代器的情况下获得相同的信息,并使迭代器成为get_key_and_client()方法的别名。