优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python中的表示函数

nanyue 2025-02-15 00:27:28 技术文章 4 ℃


I. format (value[, format_spec])

print(format(3.14159, ".2f"))  
# Output: '3.14'

II. repr(对象)

  • Python 中的 __repr__ 方法旨在提供对象的明确字符串表示形式,理想情况下,该表示可用于使用 eval() 函数重新创建对象。它对于调试非常有用,因为它清楚地显示了对象的内部状态。
  • 此函数在调试或记录信息时特别有用,因为它可以深入了解数据类型和值。

语法

repr(object)

示例:Book类

让我们创建一个简单的 Book 类来说明 __repr__ 的用法,我们还将介绍 __eq__ 以演示如何根据 Book 对象的属性来比较 Book 对象。

第 1 步:定义 Book 类

class Book:  
    def __init__(self, title, author, isbn):  
        self.title = title  
        self.author = author  
        self.isbn = isbn  

    def __repr__(self):  
        return f"Book(title={self.title!r}, author={self.author!r}, isbn={self.isbn!r})"  

    def __eq__(self, other):  
        if isinstance(other, Book):  
            # Consider books equal if they have the same ISBN
            return self.isbn == other.isbn  
        return False

第 2 步:代码解释

属性:

  • title:书名。
  • author:书籍的作者。
  • isbn: 本书的 ISBN,唯一。

__repr__方法:

  • 此方法返回一个字符串,该字符串看起来像是创建 Book 对象的调用。使用 !r 确保以适合eval() 的方式表示值,从而提供一种清晰的方式来显示对象。

__情 商__方法:

  • 此方法根据 isbn 属性检查是否相等。如果两本书具有相同的 ISBN,则它们被视为相等。

第 3 步:使用 Book 类

让我们创建一些 book 实例,看看 __repr____eq__ 在实践中是如何工作的。

# Create two book objects  
book1 = Book("1984", "George Orwell", "978-0451524935")  
book2 = Book("Nineteen Eighty-Four", "George Orwell", "978-0451524935")  # Same ISBN  
book3 = Book("Brave New World", "Aldous Huxley", "978-0060850524")  

# Use repr to get the string representation  
print(repr(book1))  
# Output: Book(title='1984', author='George Orwell', isbn='978-0451524935')  

# Check if books are equal  
print(book1 == book2)  
# Output: True, because they have the same ISBN  

print(book1 == book3)  
# Output: False, because their ISBNs are different  

# Showing that repr can recreate the object  
book_recreated = eval(repr(book1))  

print(book_recreated)  
# Output: Book(title='1984', author='George Orwell', isbn='978-0451524935')  

print(book_recreated == book1)  
# Output: True, recreated object is equal to the original
最近发表
标签列表