尝试理解子函数中 __repr__
的用途。被调用的类是针对 Flask 中的 db.model 我不知道这个函数是如何使用的以及它的目的是什么。这是 git hub 的链接,我在其中遇到了这个 https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/08-Posts/flaskblog/models.py
此代码在 MySQL 中为 Flask 网站创建表。
我已经研究了 __repr__
的目的,但我仍然无法理解它在这种情况下是如何工作的。
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(120), nullable=False)
username = db.Column(db.String(120), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(120), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
#posts = db.relationship('Aaa', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
没有错误消息,但我不明白使用它的上下文。
最佳答案
repr方法用于获取Python对象的字符串表示形式。人们在为 Flask 应用程序创建模型时使用它是很常见的。
使用repr方法,您可以从数据库进行查询并打印查询结果。 repr 方法不是获取查询对象在内存中的位置,而是提供更好的结果表示。
使用您的示例:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(120), nullable=False)
username = db.Column(db.String(120), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(120), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
#posts = db.relationship('Aaa', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
如果您的用户具有以下详细信息:
- id=1
- first_name =“比利”
- 用户名 = 'Bly'
- 电子邮件 = ' [email protected] '
- image_file = '默认.jpg'
- 密码=“样本”
打印查询结果时,您将得到:
"User('Bly', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94d6fdf8f8edfefbf1d4f6febaf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>', 'default.jpg')"
上面的结果比看起来更好:
<__main__.User object at 0x7f6882314da0>
关于python - thing 子函数用 f str 返回 __repr__ 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57647799/