Python中<>的含义

什么类型的
Python数据结构由“<>”表示,如下所示.

[<Board 1>, <Board 2>, <Board 3>]

我在使用用于Python3的Flask-SQLAlchemy库时遇到了这个问题.见下面的代码.

class Board(db.Model):

  __tablename__ = 'boards'

  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(256), unique=True, nullable=False)
  description = db.Column(db.String(256))

  def __init__(id, name, description):
    self.id = id
    self.name = name
    self.description = description


tuple_boards = Board.query.all()

print (tuple_boards)
[<Board 1>, <Board 2>, <Board 3>]

最佳答案 它不是数据结构.这就是Flask-SQLAlchemy如何将模型实例表示为
Model.__repr__的字符串:

class Model(object):
    ...

    def __repr__(self):
        identity = inspect(self).identity
        if identity is None:
            pk = "(transient {0})".format(id(self))
        else:
            pk = ', '.join(to_str(value) for value in identity)
        return '<{0} {1}>'.format(type(self).__name__, pk)

它比默认对象更有用.__ repr__:

In [1]: class Thing(object):
  ...       pass
  ...

In [2]: [Thing(), Thing(), Thing()]
Out[2]:
[<__main__.Thing at 0x10c8826a0>,
 <__main__.Thing at 0x10c8820b8>,
 <__main__.Thing at 0x10c8822e8>]

你可以在__repr__中放置你想要的任何东西,但通常最好明确地将你的对象表示为一个字符串:

In [4]: class OtherThing(object):
  ...       def __repr__(self):
  ...           return "I'm an arbitrary string"
  ...

In [5]: [OtherThing(), OtherThing()]
Out[5]: [I'm an arbitrary string, I'm an arbitrary string]

我经常看到< …>用于非有效Python代码的对象表示的字符串,因为许多其他内置对象’__repr__esentations是重构等效对象的有效Python代码.

点赞